Concurrent Collection (iii)
----------
Using the CONCURRENTMAP implementation class
The Java.util.concurrent.ConcurrentMap interface and the Concurrenthashmap implementation class can only add elements to a map if the key does not exist, and you can delete an element from the map only if the key exists and is mapped to a specific value. The following methods are mainly defined (K denotes the type of the key, V is the type of the value):
1. V putifabsent (K key,v value): If the specified key is no longer associated with a value, it is associated with the given value.
2. Boolean Remove (Object key,object value): The entry of the key is removed only if the entry of the key is currently mapped to the given value.
3. Boolean replace (K key,v oldvalue,v newvalue): Replaces the entry of the key only if it is currently mapped to a given value.
4. V replace (K key,v value): Replaces the entry of the key only if it is currently mapped to a value.
The Putifabsent () method is used to add in the map. This method takes the value of the key to be added to the concurrentmap as an argument, just like the normal put () method, but the key can be added to the map only if it is not included in the map. If the map already contains this key, the existing value of the key is retained. The Putifabsent () method is atomic. Equivalent to the following code (in addition to the atomic execution of this operation):
if (!map.containskey (key)) return
map.put (key,value);
else return
Map.get (key)
Like the Putifabsent () method, the overloaded remove () method has two parameters: a key and a value. When invoked, this key is removed from the map only if the key is mapped to a specified value. If it does not match, then the key is not deleted and false is returned. If the value matches the current mapped content of the key, the key is deleted, and the method is atomic. The equivalent source code for this operation (in addition to the atomic execution of this operation):
if (Map.containskey (key) && Map.get (key). Equals (value)) {
map.remove (key);
return true;
} else return false;
In short, the method defined in Concurrentmap is atomic.