Java 8 流的非干扰要求

2022-01-22 00:00:00 java-8 java java-stream

我是 Java 8 的初学者.

I am a beginner in Java 8.

无干扰对于保持一致的 Java 流行为很重要.想象一下,我们正在处理大量数据,并且在此过程中源变了.结果将是不可预测的.这是不考虑流并行的处理模式或顺序.

Non-interference is important to have consistent Java stream behaviour. Imagine we are process a large stream of data and during the process the source is changed. The result will be unpredictable. This is irrespective of the processing mode of the stream parallel or sequential.

源可以修改,直到语句终端操作为调用.除此之外,源不应该被修改,直到流执行完成.所以处理流中的并发修改源对于获得一致的流性能至关重要.

The source can be modified till the statement terminal operation is invoked. Beyond that the source should not be modified till the stream execution completes. So handling the concurrent modification in stream source is critical to have a consistent stream performance.

以上引文摘自这里.

有人可以做一些简单的例子来解释为什么改变流源会产生如此大的问题吗?

Can someone do some simple example that would shed lights on why mutating the stream source would give such big problems?

推荐答案

好吧 oracle example 在这里是不言自明的.第一个是这样的:

Well the oracle example is self-explanatory here. First one is this:

List<String> l = new ArrayList<>(Arrays.asList("one", "two"));
 Stream<String> sl = l.stream();
 l.add("three");
 String s = l.collect(Collectors.joining(" "));

如果你改变 l 通过添加一个元素到它之前你调用终端操作(Collectors.joining)你很好;但请注意,Stream 由三个元素组成,而不是两个;在您通过 l.stream() 创建 Stream 时.

If you change l by adding one more elements to it before you call the terminal operation (Collectors.joining) you are fine; but notice that the Stream consists of three elements, not two; at the time you created the Stream via l.stream().

另一方面,这样做:

  List<String> list = new ArrayList<>();
  list.add("test");
  list.forEach(x -> list.add(x));

将抛出 ConcurrentModificationException 因为您无法更改源.

will throw a ConcurrentModificationException since you can't change the source.

现在假设您有一个可以处理并发添加的底层源:

And now suppose you have an underlying source that can handle concurrent adds:

ConcurrentHashMap<String, Integer> cMap = new ConcurrentHashMap<>();
cMap.put("one", 1);
cMap.forEach((key, value) -> cMap.put(key + key, value + value));
System.out.println(cMap);

这里的输出应该是什么?当我运行它时:

What should the output be here? When I run this it is:

 {oneoneoneoneoneoneoneone=8, one=1, oneone=2, oneoneoneone=4}

把key改成zx (cMap.put("zx", 1)),现在的结果是:

Changing the key to zx (cMap.put("zx", 1)), the result is now:

{zxzx=2, zx=1}

结果不一致.

相关文章