What is the advantage of remove() method in traditional collection and concurrent collection in Java?

Nishant Bhardwaz :

I know the underlying difference between the remove() method of the traditional collection like hashMap and concurrent collection like concurrentHashMap. In concurrentHashmap, JVM will match the key and the value both before removing the key value object which is required for the multithreading environment. Is there any other difference between them?

Tom Hawtin - tackline :

I think you are asking why is there a second remove method in the concurrent map.

Map has:

V remove​(Object key)

ConcurrentMap has an additional method:

boolean remove​(Object key, Object value)

(In fact, Map has this as a default method since 1.8.)

In a non-concurrent Map, the two-arg form can easily written by composing a get followed by remove, at the cost of two lookups. Concurrent operations, however, do not compose. For concurrent maps you may see remove used in a loop similar to how compareAndSet is typically used.

You could perform the remove operation in a single operation through the normal collections interfaces if you first used entrySet. It's just not very convenient or obvious.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325207&siteId=1