Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is List.iterator() thread-safe?

Tags:

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?

like image 310
ubuntudroid Avatar asked May 01 '11 10:05

ubuntudroid


People also ask

Is iterator next thread-safe?

Iterators are still not threadsafe. The solution to this iteration problem will be to acquire the collection's lock when you need to iterate over it, which we'll talk about in a future reading.

Is list thread-safe in Java?

A thread-safe variant of ArrayList in which all mutative operations (e.g., add, set, remove..) are implemented by creating a separate copy of an underlying array. It achieves thread safety by creating a separate copy of the List which is different than vector or other collections used to provide thread-safety.

Is for loop thread-safe when list is modified?

Yes, but this has nothing to do with CME. Only single calls will be synchronized. So one add cannot be called while another thread is calling add, for example. But altering the list will cause the CME be thrown while iterating on another thread.

Is ArrayList get thread-safe?

Vectors are synchronized. Any method that touches the Vector 's contents is thread safe. ArrayList , on the other hand, is unsynchronized, making them, therefore, not thread safe.


1 Answers

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.

like image 170
Peter Lawrey Avatar answered Sep 30 '22 17:09

Peter Lawrey