Skip to content
Advertisement

parallelStream() java 1.8 vs 11

Consider the following code:

JavaScript

When it is compiled and run with java 11, it returns the following:

JavaScript

But with java 1.8, it returns different result:

JavaScript

Why results are different?

Advertisement

Answer

Both results are consistent with the Java Memory Model.

One possible ordering in which execution occurs is:

JavaScript

but, because you don’t do anything to ensure that the set and print occur atomically, the following is also allowed (as are many other orderings):

JavaScript

So, the reason they’re different is because the specification doesn’t require them to be the same; and some subtle (or perhaps not-so-subtle) implementation (or environmental) difference means they execute differently.

But, you say, what is the implementation difference? That’s not something you should need to care about (which sounds like bluster to cover for not knowing: I really don’t). You should care about the Java Memory Model, because that gives the guaranteed properties.

For example, if you want the “Java 8” behaviour, you can synchronize the threads on a common monitor, for example obj:

JavaScript

Of course, the threads still will execute in an arbitrary order; but each thread will print the value that it set.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement