How does ConcurrentHashMap behave in multithreaded code?

ConcurrentHashMap is a part of the Java Collections Framework that allows concurrent access and modifications to a map without needing to lock the entire structure. This means that multiple threads can read from and write to the map simultaneously without causing thread interference or consistency issues.

It behaves differently compared to a synchronized HashMap. With ConcurrentHashMap, reads are non-blocking and writes are done in segments, which allows for higher concurrency and better performance when multiple threads interact with the map.

Here is a simple example of how ConcurrentHashMap can be used in a multithreaded environment:

import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap map = new ConcurrentHashMap<>(); // Adding elements map.put(1, "One"); map.put(2, "Two"); // Start a thread to update the map Thread thread1 = new Thread(() -> { map.put(3, "Three"); System.out.println("Thread 1 added 3"); }); // Start a thread to read from the map Thread thread2 = new Thread(() -> { System.out.println("Thread 2 read: " + map.get(1)); }); thread1.start(); thread2.start(); // Wait for threads to finish try { thread1.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Final map: " + map); } }

ConcurrentHashMap multithreading Java collections concurrency