java - 执行流操作 java 8 时正在更新集合

标签 java java-8 java-stream

我有一个 List 对象,这些对象会定期从几个线程中更新。在更新时,我想使用流来过滤掉一些元素。

例如;假设我有定期更新的列表:

List<MyObject> myList

现在在某个时间点我在那个列表上使用流

List<MyObject> result =  
myList.stream().filter(myobj->myobjt.isValid()).collect(toList());

考虑到我的列表是从几个线程更新的,这是线程安全的吗?

最佳答案

Javadoc of CopyOnWriteArrayList陈述如下:

The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created.

所以,是的,您的代码应该是线程安全的。流将在开始后忽略列表中的所有添加。

关于java - 执行流操作 java 8 时正在更新集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30229585/

相关文章:

java - 为什么共享可变性不好?

java - 使用流 StreamSupplier

java - 将 map 转换为 map 列表

functional-programming - Java 8函数样式以索引进行迭代

java - 当原始 map 包含集合作为值时,如何创建反向 map ?

java - 如何仅传递用户选择的字符串

java - SimpleDateFormat解析时间时出现parseException

java - 如何通过正则表达式检测奇数长度的01序列

java - 我的元素列表 xpath 的计数为 0

java - 为什么 .forEach(val -> list.add()) 编译而 .forEach(val -> true) 不编译?