Consider the following code:
public class StreamDemo {
public static void main(String[] args) {
StreamObject obj = new StreamObject();
obj.setName("mystream");
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
list.parallelStream().forEach(l -> {
obj.setId(l);
System.out.println(obj + Thread.currentThread().getName());
});
}
static public class StreamObject {
private String name;
private Integer id;
// getters, setters, toString()
}
}
When it is compiled and run with java 11, it returns the following:
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-23
StreamObject{name='mystream', id=4}main
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-9
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-5
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-19
But with java 1.8, it returns different result:
StreamObject{name='mystream', id=3}main
StreamObject{name='mystream', id=5}ForkJoinPool.commonPool-worker-2
StreamObject{name='mystream', id=2}ForkJoinPool.commonPool-worker-9
StreamObject{name='mystream', id=1}ForkJoinPool.commonPool-worker-11
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-4
Why results are different?