简体   繁体   中英

Why is there a 'remove(key, value)' method in the Map interface?

I just found out that Map exposes a method for " [removing] the entry for the specified key only if it is currently mapped to the specified value. ". It is defined as:

default boolean remove(Object key, Object value)

I fail to come up with reasons to include this method in the interface of my own custom maps. I'm curious, why would anyone want to do this? Can someone provide an example of an algorithm irreplaceable by the default remove(key) (without the 'value' parameter)?

The Javadoc of that method explains it:

The default implementation is equivalent to, for this map:

 if (map.containsKey(key) && Objects.equals(map.get(key), value)) { map.remove(key); return true; } else return false;

The default implementation makes no guarantees about synchronization or atomicity properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties.

In general, as long as you don't have atomicity guarantees, don't override it and use the default implementation above.

This is useful in concurrent programming when multiple threads access the same Map. You would need a ConcurrentHashMap which provides atomicity guarantees for remove(Object, Object) .

For example, smth like that (imagine ConcurrentHashMap<String, String> cache is shared between threads):

String key = ...;
String value = cache.get(key);
//long lasting operation
cache.remove(key, value);

During that "long lasting operation", another thread might have updated the value assigned to key . You only want the key to be removed if it is still assigned to the same value as before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM