Working with Concurrent Hash Map in Java

Introduction

In this article we will see how ConcurrentHashMap is works. In Java, the ConcurrentHashMap is a thread-safe implementation of the Map interface. It provides concurrent access to a hash table, allowing multiple threads to read and modify the map concurrently, without the need for external synchronization. This makes it particularly useful in multi-threaded environments, where multiple threads need to access and manipulate shared data concurrently.

The ConcurrentHashMap achieves thread-safety by partitioning the map into smaller segments, each of which can be operated on independently by different threads. This partitioning is transparent to the user and improves the performance of concurrent access compared to using synchronization mechanisms like synchronized blocks or ReentrantLock. Let's take an example of ConcurrentHashMap.

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

        // Put key-value pairs into the map
        map.put("apple", 1);
        map.put("banana", 2);
        map.put("orange", 3);

        // Get the value for a key
        Integer value = map.get("banana");
        System.out.println("Value for 'banana': " + value); // Output: Value for 'banana': 2

        // Remove a key-value pair
        map.remove("orange");

        // Iterate over the map (thread-safe)
        for (String key : map.keySet()) {
          //Updating the ConcurrentHashMap
            map.put("grapes", 4);
            System.out.println("Key: " + key + ", Value: " + map.get(key));
        }
    }
}

In the above example, I have create a new ConcurrentHashMap instance and perform various operations on it, such as putting key-value pairs, getting the value for a key, removing a key-value pair, and iterating over the map. The iteration is thread-safe, meaning that other threads can modify the map concurrently without causing issues and you can see above i am updating the ConcurrentHashMap.

Summary

ConcurrentHashMap in Java provides a thread-safe and efficient way to manage shared data in multi-threaded environments. Its partitioning approach ensures high performance while maintaining thread safety, making it a valuable tool for building concurrent applications.


Similar Articles