为什么锁定线程安全集合? [英] Why lock Thread safe collections?

查看:104
本文介绍了为什么锁定线程安全集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.concurrent提供了许多线程安全的集合,例如 ConcurrentHashMap ConcurrentSkipListMap ConcurrentSkipListSet ConcurrentLinkedQueue 。这些集合应该通过允许同时访问数据结构的不同部分来最小化争用。

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还具有同步包装器,允许并发访问非线程安全集合,例如 HashMap Arraylist

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?

有没有办法我们可以提供线程安全集合而不使用同步?我熟悉volatile关键字可以潜在地用于非原子操作的原始值。

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)所以回答你的第二个问题自动成为yes。

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)关于没有使用同步的线程安全收集 :这是一个听起来像一个可能是困难的任务,应该是开发平台的开发人员团队容易的东西。但在现实中,这是一个噩梦在多核环境和侵略性优化的时代。在功能(可能听起来像这样简单)和性能(在处理器缓存中同步需要大量的时间)之间总是存在权衡。请参阅Angelica Langer的视频(针对java内存模型)。

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).

希望这有助。

这篇关于为什么锁定线程安全集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆