Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection being updated while performing stream operation java 8

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?

like image 759
user1409534 Avatar asked May 14 '15 05:05

user1409534


1 Answers

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.

like image 89
Thilo Avatar answered Sep 16 '22 15:09

Thilo