ConcurrentHashMap Class
ConcurrentHashMap is a class that provides the same functionalities as a HashTable (not HashMap, as it does not allow using null as a key or value).
If we were to use a classic HashMap and add a lock for accessing the structure, it would not be very efficient because only one thread could access it at any given time. This is unnecessary if, for example, different threads want to modify different elements. On the other hand, if we were to use a lock for each element, we would need quite a few locks, which could complicate our work.
In a ConcurrentHashMap, get and put operations block access to a specific element (they have mutexes in their implementation) but DO NOT block access to the entire data structure. In other words, two or more threads can access it simultaneously, and get operations can overlap with update operations (put). However, the implementation ensures that the get operations are executed at the end after the update operations have completed.
The most commonly used methods include:
- get(key) - returns the value associated with a key
- contains(val) - checks if a value exists in the map
- containsKey(key) - checks if a key exists in the map
- put(key, val) - adds a value to the specified key
- putIfAbsent(key, val) - adds an association only if there is no existing value for that key; it returns the old value if one exists, otherwise it returns null
- remove(key) - deletes a key-value association
- replace(key, val) - modifies the value associated with a key.
You can see an example of usage below.
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<Integer, String>();
map.put(0, "Zero");
map.put(1, "One");
System.out.println(map.get(1)); // One
// Attempt to put "Unu" for key 1, but no modification occurs; val will be "One"
String val = map.putIfAbsent(1, "Unu");
// Put the mapping 2-"Two" into the map; val will be null
val = map.putIfAbsent(2, "Two");