non-interference requirement on Java 8 streams(Java 8 流的非干扰要求)
问题描述
我是 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}
结果不一致.
这篇关于Java 8 流的非干扰要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 流的非干扰要求


基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- Java Swing计时器未清除 2022-01-01