java.util.concurrent provides many thread safe collections like ConcurrentHashMap
, ConcurrentSkipListMap
, ConcurrentSkipListSet
and ConcurrentLinkedQueue
. These collections are supposed to minimize contention by allowing concurrent access to different parts of the data structure.
Java also has synchronized wrappers to allow concurrent access to non thread safe collections like HashMap
and Arraylist
.
Map<KeyType, ValType> m = Collections.synchronizedMap(new HashMap<KeyType, ValType>());
Do we still need to perform client side locking when dealing with these thread safe collections? Especially, while doing something iterating over them?
Set<KeyType> s = m.keySet();
synchronized(m) {
for (KeyType k : s)
foo(k);
}
In this context, is thread safety provided for only certain kinds of operations?
Is there a way we could provided thread safe collections without using synchronization? I am familiar with the volatile keyword that can potentially be used with primitive values for non atomic operations.