I have a List
of objects that are being updated on a regular basis from a couple of threads. While being updated I want to use a stream to filter some elements out.
For example; say I have list that is being updated regularly:
List<MyObject> myList
Now at some point in time I use stream on that list
List<MyObject> result =
myList.stream().filter(myobj->myobjt.isValid()).collect(toList());
Is this thread-safe given that my list is being update from a couple of threads?
The Javadoc of CopyOnWriteArrayList states the following:
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.
So, yes, your code should be threadsafe. The stream will ignore all additions to the list after it has started.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With