Why lock Thread safe collections?

时间秒杀一切 提交于 2019-12-24 05:03:14

问题


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.


回答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.



来源:https://stackoverflow.com/questions/21501808/why-lock-thread-safe-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!