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 流的非干扰要求
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01