Java Concurrent HashMap And Example
Java ConcurrentHashMap
is a thread-safe implementation of the Map
interface in Java that allows multiple threads to read and write to the map concurrently without causing any inconsistencies or data corruption. It achieves thread-safety by dividing the map into segments, and different threads can access different segments concurrently.
Here’s an example of using ConcurrentHashMap
:
import java.util.concurrent.ConcurrentHashMap;
public class Example {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// Add key-value pairs to the map
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// Retrieve a value from the map
int value = map.get("banana"); // returns 2
// Replace a value in the map
int oldValue = map.replace("orange", 4);
if (oldValue != null) {
System.out.println("The old value of orange was " + oldValue);
}
// Remove a key-value pair from the map
map.remove("apple");
// Get the size of the map
int size = map.size();
System.out.println("The size of the map is " + size);
}
}
This example creates a ConcurrentHashMap
that maps strings to integers. It adds three key-value pairs to the map, retrieves the value associated with the "banana" key, replaces the value associated with the "orange" key with a new value, removes the "apple" key and its associated value from the map, and prints the size of the map. All of these operations can be performed concurrently by multiple threads without any issues.