Jordi
Jordi

Reputation: 23197

Iterate over collection in multithread environment: ConcurrentModificationException

I'm getting a ConcurrentModificationException since this code is reached by several threads at the same time:

public void flush(Audit... audits) {
   // Copy first them on memory
   this.pendingAudits.addAll(Arrays.asList(audits));

   for (Iterator<Audit> it = this.pendingAudits.iterator(); it.hasNext();) {
       // Do something
       it.remove();
   }
}

I'm getting an iterator over pendingAudits and I'm removing each element at the same time other threads can add some other audits.

How to solve it elegantly?

Upvotes: 1

Views: 66

Answers (1)

rustyx
rustyx

Reputation: 85286

A quick solution is to wrap every access to this.pendingAudits in synchronized:

sychronized(this.pendingAudits) {
   this.pendingAudits.addAll(Arrays.asList(audits));

   for (Iterator<Audit> it = this.pendingAudits.iterator(); it.hasNext();) {
       // Do something
       it.remove();
   }
}

The net effect will be that at any given time only one thread can be executing the synchronized block. That can become a bottleneck if the code is executed frequently.

Upvotes: 2

Related Questions