How to use ConcurrentHashMap in Java?

In Java, ConcurrentHashMap is a thread-safe implementation of a hash table that provides better concurrent performance than HashMap. Here is a simple example demonstrating how to use ConcurrentHashMap:

import java.util.concurrent.ConcurrentHashMap;

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

        // 添加元素
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);

        // 获取元素
        System.out.println("Value of key A: " + map.get("A"));

        // 遍历元素
        map.forEach((key, value) -> {
            System.out.println(key + " : " + value);
        });

        // 使用compute方法更新元素
        map.compute("A", (key, value) -> value * 10);
        System.out.println("Value of key A after compute: " + map.get("A"));

        // 使用remove方法删除元素
        map.remove("B");
        System.out.println("Value of key B after remove: " + map.get("B"));

        // 检查元素是否存在
        System.out.println("Is key C present? " + map.containsKey("C"));
    }
}

In the example above, we start by creating a ConcurrentHashMap object and adding elements using the put method. We then retrieve the value of a specific key using the get method, iterate through all elements using the forEach method, update elements using the compute method, remove elements using the remove method, and finally check if a specified key exists using the containsKey method.

It is important to note that ConcurrentHashMap is thread-safe, so multiple threads can read and write to it concurrently without causing conflicts. Therefore, ConcurrentHashMap is highly suitable for use in a multi-threaded environment.

bannerAds