How do you use ConcurrentHashMap with a simple code example?

ConcurrentHashMap is part of the Java Collections Framework and provides a thread-safe implementation of the Map interface. It is particularly useful in concurrent programming where multiple threads need to read and write to a shared map without running into concurrency issues. Unlike the traditional HashMap, ConcurrentHashMap allows for high concurrency and is designed for situations where reads are more frequent than writes.

Here is a simple example of using ConcurrentHashMap:

import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap map = new ConcurrentHashMap<>(); // Putting values in the map map.put("Apple", 1); map.put("Banana", 2); map.put("Orange", 3); // Accessing values System.out.println("Apple count: " + map.get("Apple")); // Removing a value map.remove("Banana"); // Iterating over the map map.forEach((key, value) -> { System.out.println(key + ": " + value); }); } }

ConcurrentHashMap Java Collections Multi-threading Thread-safe Concurrent Programming