Search code examples
javacollectionsjava.util.concurrent

How to make sure elements of a concurrent list in java, that are added after the list has been looped through, are handled properly?


I have a concurrent list of objects. Multiple threads add to this list. At some point I loop through this list and perform operations on the list elements. How do I ensure that I process the elements that are added while looping through the list?

Main Thread:

List<Object> someList = Collections.synchronizedList(new ArrayList<Object>());
for(Object o : someList){
    o.toString();
}

Some other Thread:

getSomeList().add(new Object());

Note: I want to process the object after i start looping through the list (or after that).


Solution

  • Using a synchronized java.util.List won't work since the iterator becomes invalid as soon as the source list is modified. Sounds like you have a producer-consumer problem. You should look into a Queue. Try java.util.Concurrent.LinkedBlockingQueue if you want an unbounded queue or java.util.concurrent.ArrayBlockingQueue if you want a blocking queue.