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 流的非干扰要求
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01