Java 8流的无干扰要求 [英] non-interference requirement on Java 8 streams

查看:132
本文介绍了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 示例在这里不言自明。第一个是:

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}

将密钥更改为 zx cMap.put(zx,1)),结果现在是:

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

{zxzx=2, zx=1}

结果不一致。

这篇关于Java 8流的无干扰要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆