A quote from #JCIP :
\"Since a ConcurrentHashMap cannot be locked for exclusive access, we cannot use client-side locking to create new atomic operatio
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
.
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."