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