25

In Java: Is List.iterator() thread-safe, i.e. does the returned iterator reflect the current state of the list at any time or just the state of the list at the time of its creation?

Vlad
  • 18,195
  • 4
  • 41
  • 71
ubuntudroid
  • 3,680
  • 6
  • 36
  • 60

3 Answers3

39

The behaviour of List.iterator() is not defined or consistent with different List implementations.

For ArrayList, LinkedList, you can get a ConcurrentModificationException if the list is modified when you are iterating over it. (This is not guaranteed) The way to avoid this issue is to use a synchronizedList() and lock the list while iterating over it.

For Vector, the collection is synchronized, but the iterator is not thread safe.

For CopyOnWriteArrayList, you get a snapshot of the elements in the list at the time you call iterator(), This iterator is thread safe, and you don't need to use any locking. Note: the contents of the elements can change.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
15

No iterator is thread-safe. If the underlying collection is changed amidst iteration, a ConcurrentModificationException is thrown.

Even iterators of synchronized collections are not thread-safe - you have to synchronize manually.

One exception is the CopyOnWriteArrayList, which holds a snapshot during iteration.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 3
    "No iterator is thread safe except one" could have been written as "All are thread safe except two or three" ;) – Peter Lawrey May 01 '11 at 11:07
  • 1
    If the underlying collection is changed during iteration by another thread, CME may be thrown or may be not thrown, since internal modification counter is not atomic. – Anton Jan 05 '17 at 00:10
0

It depends on what class you use,

not for Collections.synchronizedList(new ArrayList<>()); reason but

for CopyOnWriteArrayList reason.

best Description here

Ali Bagheri
  • 3,068
  • 27
  • 28