Thread-safe iteration over a collection Thread-safe iteration over a collection multithreading multithreading

Thread-safe iteration over a collection


You've already answered your bonus question really: no, using an enhanced for loop isn't safe - because it uses an iterator.

As for which is the most appropriate approach - it really depends on how your context:

  • Are writes very infrequent? If so, CopyOnWriteArrayList may be most appropriate.
  • Is the collection reasonably small, and the iteration quick? (i.e. you're not doing much work in the loop) If so, synchronizing may well be fine - especially if this doesn't happen too often (i.e. you won't have much contention for the collection).
  • If you're doing a lot of work and don't want to block other threads working at the same time, the hit of cloning the collection may well be acceptable.


Depends on your access model. If you have low concurrency and frequent writes, 1 will have the best performance. If you have high concurrency with and infrequent writes, 3 will have the best performance. Option 2 is going to perform badly in almost all cases.

foreach calls iterator(), so exactly the same things apply.


You could use one of the newer collections added in Java 5.0 which support concurrent access while iterating. Another approach is to take a copy using toArray which is thread safe (during the copy).

Collection<String> words = ...// enhanced for loop over an array.for(String word: words.toArray(new String[0])) {}