Why ConcurrentHashMap cannot be locked for exclusive access?

不羁岁月 提交于 2019-12-01 22:11:53

Why? Because the implementation does not support it. Straight from the 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."

The whole point of the ConcurrentHashMap is that read operations never block, i.e. do not have to check for locks. 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.

Code you have written is your implementation, and if you use it that way then all other operations must work that way i.e. 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.

For your requirement go for HashTable.

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