Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

java - Is List.iterator() thread-safe?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...