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.
How to make sure elements of a concurrent list in java, that are added after the list has been looped through, are handled properly?
-
29-06-2022 - |
Domanda
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).
Soluzione
Altri suggerimenti
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.