Sample Java Stream State Representation

the package summary java.util.stream

reads as follows:

An example of a stateful lambda is a parameter map()

in:

Set<Integer> seen = Collections.synchronizedSet(new HashSet<>());
stream.parallel().map(e -> { if (seen.add(e)) return 0; else return e; })...

      

Here, if the matching operation is performed in parallel, the results for the same input may differ from run to run due to differences in thread scheduling, whereas with a stateless lambda expression, the results will always be the same.

I don't understand why this would not produce consistent results, given that the set is synchronized and can only handle one item at a time. Can you complete the above example in such a way as to show how the result might change due to parallelization?

+3


source to share


2 answers


List<Integer> numbers = // fill it in with [1, 3, 3, 5]
List<Integer> collected = numbers.stream().parallel().map(...).collect(Collectors.toList());

      



collected

can contain either [0, 0, 3, 0] or [0, 3, 0, 0], depending on which middle element was processed first.

+3


source


I'm not sure if this counts as a state in terms of state (if it doesn't, I'll just delete it), but rely on anything that has state inside map

, etc. badly.

int[] arr = new int[3];
    Stream.of(1, 2, 3)
            .map(i -> {
                arr[i] = i + 5;
                return i * 2;
            })
            .count();

    System.out.println(Arrays.toString(arr));

      



In jdk-9, an array with only zeros will be created, as there are no operations that resize the stream ( flatmap

or filter

), so it map

never gets executed.

+2


source







All Articles