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);
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?