2

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.

Tanmay Patil
  • 6,882
  • 2
  • 25
  • 45
Pha3drus
  • 169
  • 1
  • 1
  • 10

1 Answers1

1

1) Yes, you need to perform client side locking while iterating, but most other methods do not require you to do it. Please refer to Explain synchronization of collections when iterators are used?

2) So answer to your second questions automatically becomes yes. You can see which operations are thread safe in the documentation (most of them are).

3) Regarding thread-safe collection without using synchronization: It's something that sounds as a maybe difficult task which should be easy for team of pro devs who develop the platform. But in reality, it's a nightmare in the era of multi-core environments and aggressive optimizations. There will always be a trade-off between functionality (which might sound as simple as this one) and performance (synchronization in processor cache takes huge amount of time). Please refer to Angelica Langer's video (on java memory model).

Hope this helps.

Community
  • 1
  • 1
Tanmay Patil
  • 6,882
  • 2
  • 25
  • 45