java concurrent collection concurrenthashmap examples
ConcurrentHashMap
is a thread-safe implementation of the Map
interface provided by Java's concurrency utilities. It is designed to provide high concurrency and performance when multiple threads are accessing and modifying the map simultaneously.
Here are some examples of how to use ConcurrentHashMap
in Java:
- Creating a
ConcurrentHashMap
:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
- Inserting values into the map:
map.put("key1", 1); map.put("key2", 2);
- Accessing values from the map:
int value = map.get("key1");
- Iterating over the keys or values in the map:
for (String key : map.keySet()) { System.out.println("Key: " + key + ", Value: " + map.get(key)); } for (Integer value : map.values()) { System.out.println("Value: " + value); }
- Updating values in the map:
map.replace("key1", 10);
- Removing values from the map:
map.remove("key2");
- Using the
compute()
method to update values based on their current value:
map.compute("key1", (k, v) -> v + 1);
- Using the
merge()
method to combine existing and new values:
map.merge("key3", 3, (v1, v2) -> v1 + v2);
ConcurrentHashMap
provides several other methods for working with the map, such as putIfAbsent()
, remove()
with a key-value pair, and atomic methods such as putIfAbsent()
, remove()
and replace()
.
ConcurrentHashMap
is a great choice for multi-threaded applications where multiple threads need to read and write to a shared map concurrently. It provides high concurrency, scalability, and performance, and also ensures that data integrity is maintained across all threads.