Domanda

A quote from #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"

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

È stato utile?

Soluzione 2

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top