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

Collection being updated while performing stream operation java 8

我有 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.

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