We all know when using Collections.synchronizedXXX
(e.g. synchronizedSet()
) we get a synchronized "view" of the underlying collection.
However, the document of these wrapper generation methods states that we have to explicitly synchronize on the collection when iterating of the collections using an iterator.
Which option do you choose to solve this problem?
I can only see the following approaches:
- Do it as the documentation states: synchronize on the collection
- Clone the collection before calling
iterator()
- Use a collection which iterator is thread-safe (I am only aware of
CopyOnWriteArrayList
/Set)
And as a bonus question: when using a synchronized view - is the use of foreach/Iterable thread-safe?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…