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

StackOverflow https://stackoverflow.com/questions/18904055

Question

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).

Was it helpful?

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.

OTHER TIPS

The only way to be able to add elements in thread A while thread B is looping through the list is for thread B make a copy of the list as it is at that exact point in time, then getting an Iterator or Enumerator from it. If you don't make a copy before looping, then you'll get a ConcurrentModificationException if another thread adds an element while the other thread is looping.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top