Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream from modified collection

Say I have a List of objects that being modified by only one thread (the thread can add or remove objects) and and another thread occasinally uses stream api from the above collecion to do some stream manipulation of it and at the end (eager operation) return a new collection. Is this a thread safe scenario? after all only one thread updates the collection.

like image 330
user1409534 Avatar asked May 18 '15 10:05

user1409534


1 Answers

This totally depends on your source List implementation. With ArrayList you may get ConcurrentModificationException (or may get corrupted data or some other exception: see the comment). With CopyOnWriteArrayList you can safely use stream operations: they will see the state of the list which was actual when the stream was created. In any case you should check the documentation for spliterator() method of the corresponding collection to see whether it's safe to use it in concurrent environment.

like image 124
Tagir Valeev Avatar answered Sep 23 '22 01:09

Tagir Valeev