简体   繁体   English

为什么无法锁定ConcurrentHashMap以进行独占访问?

[英]Why ConcurrentHashMap cannot be locked for exclusive access?

A quote from #JCIP : 来自#JCIP的引用:

"Since a ConcurrentHashMap cannot be locked for exclusive access, we cannot use client-side locking to create new atomic operations such as put-if-absent, as we did for Vector" “由于ConcurrentHashMap无法被锁定以进行独占访问,因此我们无法使用客户端锁定来创建新的原子操作,例如put-if-absent,就像我们为Vector所做的那样”

Why we can't just acquire the lock in order to implement additional atomic methods and keep the collection thread-safe (like synchronized collections returned by Collections.synchronizedxxx factory) : 为什么我们不能只是获取以实现其他原子方法并保持集合线程安全 (如Collections.synchronizedxxx工厂返回的同步集合):

The whole point of the ConcurrentHashMap is that read operations never block, ie do not have to check for locks. ConcurrentHashMap的重点是读操作永远不会阻塞,即不必检查锁。 That precludes the ability to have such a lock. 这就排除了拥有这种锁定的能力。

Why we can't just acquire the lock : 为什么我们不能只获得锁定:

You could do that, but you have to do it consistently for all access paths to the map, and then you have completely negated to purpose of a concurrent data structure. 你可以这样做,但你必须为地图的所有访问路径一致地做,然后你完全否定了并发数据结构的目的。 It is supposed to be lock-free. 它应该是无锁的。

Why? 为什么? Because the implementation does not support it. 因为实现不支持它。 Straight from the ConcurrentHashMap JavaDocs: 直接来自ConcurrentHashMap JavaDocs:

There is not any support for locking the entire table in a way that prevents all access 没有任何支持以阻止所有访问的方式锁定整个表

...which is, by definition, "exclusive access." ......根据定义,“独家访问”。

Code you have written is your implementation, and if you use it that way then all other operations must work that way ie all operations must accquire same lock. 您编写的代码是您的实现,如果您以这种方式使用它,那么所有其他操作必须以这种方式工作,即所有操作必须获得相同的锁。

But the main point here is that java has not provided ConcurrentHashMap for this purpose, its purpose is to allow multiple thread to work simultaneously. 但这里的要点是java没有为此提供ConcurrentHashMap ,其目的是允许多个线程同时工作。

For your requirement go for HashTable . 根据您的要求,选择HashTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM