Search code examples
javacollectionsqueueconcurrentmodification

Will I get ConcurrentModificationException if I add objects to a Queue as I'm going through it?


I wasn't sure how to form the question..

Basically I have this code:

java.util.Queue myQueue;

...

myQueue.stream().filter(particle -> particle instanceof ParticleDigging).forEach(particle -> {
     myQueue.add(new ParticleSmoke());
});

Now what I want to know is if it would throw a ConcurrentModificationException at some point.

Can it even throw the exception with .stream()?


Solution

  • You could use a ConcurrentLinkedQueue implementation for your queue. If you look at the java docs they do not throw a concurrentModificationException because internally it uses an iterator.

    ConcurrentLinkedQueue

    Queue<Particle> myQueue = new ConcurrentLinkedQueue<>();
    

    if you convert to a stream then stream makes a spliterator which has the same effect:

    default Stream<E> stream() {
            return StreamSupport.stream(spliterator(), false);
        }