简体   繁体   English

Java Stream有状态行为示例

[英]Java Stream stateful behavior example

The package summary of java.util.stream states the following: java.util.stream软件包摘要声明如下:

An example of a stateful lambda is the parameter to map() in: 有状态lambda的一个例子是map()的参数:

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

Here, if the mapping operation is performed in parallel, the results for the same input could vary from run to run, due to thread scheduling differences, whereas, with a stateless lambda expression the results would always be the same. 这里,如果映射操作是并行执行的,则由于线程调度差异,相同输入的结果可能因运行而不同,而对于无状态lambda表达式,结果将始终相同。

I don't understand why this wouldn't produce consistent results, given that the set is synchronized and can only process one element at a time. 我不明白为什么这不会产生一致的结果,因为该集是同步的,并且一次只能处理一个元素。 Can you complete the above example in a way that demonstrates how the result could vary due to parallelization? 您能否以一种演示结果如何因并行化而变化的方式完成上述示例?

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

collected could contain either [0, 0, 3, 0] or [0, 3, 0, 0], depending on which of the middle two elements was processed first. collected可以包含[0,0,3,0]或[0,3,0,0],具体取决于首先处理中间两个元素中的哪一个。

I'm not sure if this counts as a stateful per-se (if it does not I'll just delete this), but relying on anything that has state inside map and the like is bad. 我不确定这是否算作有状态本身(如果它不是我只会删除它),但依赖于任何具有状态内部map等的东西都是坏的。

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 this will produce an array with zeroes only, since there are no operations that change the Stream size ( flatmap or filter ), thus map is never executed. 在jdk-9中,这将生成仅具有零的数组,因为没有操作可以更改Stream大小( flatmapfilter ),因此从不执行map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM