Collection is updated when working with java 8 stream

I have a List objects that are regularly updated from multiple threads. During the update, I want to use a stream to filter some elements.

For instance; I have a list that is regularly updated:

 List<MyObject> myList 

Now at some point in time I use the stream in this list

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

Is this thread safe considering my list is being updated from multiple threads?

+6
source share
1 answer

The Javadoc of CopyOnWriteArrayList states the following:

The snapshot style iterator method uses a reference to the state of the array at the point at which the iterator was created. This array never changes during the life of the iterator, so no interference is possible, and the iterator is guaranteed not to throw a ConcurrentModificationException. The iterator will not display additions, deletions, or changes to the list since the creation of the iterator.

So yes, your code should be thread safe. The stream will ignore all additions to the list after it starts.

+7
source

Source: https://habr.com/ru/post/987176/


All Articles