The ConcurrentHashMap class in Java is a thread-safe version of the HashMap class. It provides concurrent access to the map, which means that multiple threads can read and write to the map at the same time without causing any issues. The ConcurrentHashMap class achieves this by partitioning the map into several smaller pieces called segments, each of which can be accessed and modified independently.
When a thread needs to read or write to the map, it first acquires a lock on the relevant segment, rather than on the entire map. This means that multiple threads can access different segments of the map simultaneously, allowing for more efficient concurrent access. Additionally, the ConcurrentHashMap class provides methods that are specifically designed for concurrent access, such as putIfAbsent(), replace(), and remove().
Here is an example of using ConcurrentHashMap in Java:
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExample {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// Adding elements to the map
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
// Retrieving elements from the map
System.out.println("Value of 'one': " + map.get("one"));
System.out.println("Value of 'two': " + map.get("two"));
System.out.println("Value of 'three': " + map.get("three"));
// Updating an element in the map
map.replace("two", 22);
System.out.println("Value of 'two' after replacement: " + map.get("two"));
// Removing an element from the map
map.remove("three");
System.out.println("Value of 'three' after removal: " + map.get("three"));
}
}
Output:
Value of 'one': 1
Value of 'two': 2
Value of 'three': 3
Value of 'two' after replacement: 22
Value of 'three' after removal: null
In this example, we create a ConcurrentHashMap instance and add some key-value pairs to it using the put() method. We then retrieve elements from the map using the get() method and update the value of an element using the replace() method. Finally, we remove an element from the map using the remove() method. Note that multiple threads can perform these operations on the map concurrently without causing any issues.
Overall, the ConcurrentHashMap class is a useful tool for concurrent programming in Java, as it allows multiple threads to access a shared map concurrently in a safe and efficient manner.