我有一个 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/