We all know when using Collections.synchronizedXXX
(e.g. synchronizedSet()
) we get a synchronized \"view\" of the underlying collection.
Ho
All three of your options will work. Choosing the right one for your situation will depend on what your situation is.
CopyOnWriteArrayList
will work if you want a list implementation and you don't mind the underlying storage being copied every time you write. This is pretty good for performance as long as you don't have very big collections.
ConcurrentHashMap
or "ConcurrentHashSet
" (using Collections.newSetFromMap
) will work if you need a Map
or Set
interface, obviously you don't get random access this way. One great! thing about these two is that they will work well with large data sets - when mutated they just copy little bits of the underlying data storage.
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])) {
}