Mastering Java ConcurrentHashMap: Operations, Examples, and Best Practices
Java ConcurrentHashMap
Explore the Java ConcurrentHashMap class, learn how to create and manipulate it, and discover its key advantages with practical code examples.
The ConcurrentHashMap class from the Java collections framework offers a thread‑safe map implementation. Multiple threads can read and write concurrently without corrupting the map’s integrity.
It implements the ConcurrentMap interface and is part of java.util.concurrent.
Create a ConcurrentHashMap
First, import the class:
import java.util.concurrent.ConcurrentHashMap;
Then instantiate it. You can specify an initial capacity and load factor, or rely on the defaults.
// Capacity 8, load factor 0.6
ConcurrentHashMap<Key, Value> numbers = new ConcurrentHashMap<>(8, 0.6f);
Parameters
capacity– the initial number of buckets (8 in the example).loadFactor– triggers a resize when the map reaches 60% full.
Default constructor creates a map with a capacity of 16 and a load factor of 0.75:
ConcurrentHashMap<Key, Value> numbers1 = new ConcurrentHashMap<>();
Creating ConcurrentHashMap from Existing Maps
You can populate a new ConcurrentHashMap with the entries of any other map.
import java.util.concurrent.ConcurrentHashMap;
import java.util.HashMap;
class Main {
public static void main(String[] args) {
HashMap<String, Integer> evenNumbers = new HashMap<>();
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
System.out.println("HashMap: " + evenNumbers);
ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>(evenNumbers);
numbers.put("Three", 3);
System.out.println("ConcurrentHashMap: " + numbers);
}
}
Output
HashMap: {Four=4, Two=2}
ConcurrentHashMap: {Four=4, Two=2, Three=3}
Key Methods of ConcurrentHashMap
Inserting Elements
put(K key, V value)– Adds or replaces a mapping.putAll(Map<? extends K, ? extends V> m)– Bulk insertion.putIfAbsent(K key, V value)– Inserts only if the key is absent.
ConcurrentHashMap<String, Integer> evenNumbers = new ConcurrentHashMap<>();
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
evenNumbers.putIfAbsent("Six", 6);
System.out.println("Even numbers: " + evenNumbers);
ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
numbers.put("One", 1);
numbers.putAll(evenNumbers);
System.out.println("Numbers: " + numbers);
Output
Even numbers: {Six=6, Four=4, Two=2}
Numbers: {Six=6, One=1, Four=4, Two=2}
Accessing Elements
Use view collections or key/value retrieval methods.
entrySet(),keySet(),values()– Return collections of entries, keys, or values.get(K key)– Retrieve a value ornullif absent.getOrDefault(K key, V defaultValue)– Retrieve a value or a provided default.
ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("Map: " + numbers);
System.out.println("Entries: " + numbers.entrySet());
System.out.println("Keys: " + numbers.keySet());
System.out.println("Values: " + numbers.values());
int val = numbers.get("Three");
System.out.println("get(\"Three\"): " + val);
int def = numbers.getOrDefault("Five", 5);
System.out.println("getOrDefault(\"Five\", 5): " + def);
Output
Map: {One=1, Two=2, Three=3}
Entries: [One=1, Two=2, Three=3]
Keys: [One, Two, Three]
Values: [1, 2, 3]
get("Three"): 3
getOrDefault("Five", 5): 5
Removing Entries
remove(K key)– Deletes the mapping and returns its value.remove(K key, V value)– Deletes only if the current value matches; returns a boolean.
ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
int removed = numbers.remove("Two");
System.out.println("Removed value: " + removed);
boolean deleted = numbers.remove("Three", 3);
System.out.println("Entry {Three=3} removed? " + deleted);
System.out.println("Updated map: " + numbers);
Output
Removed value: 2
Entry {Three=3} removed? true
Updated map: {One=1}
Bulk Operations
These methods leverage parallelism to process large maps efficiently.
forEach()
Iterates over entries, optionally in parallel, and applies a consumer.
numbers.forEach(4, (k, v) -> System.out.println("key: " + k + " value: " + v));
// With a transformer:
numbers.forEach(4, (k, v) -> v, (v) -> System.out.print(v + ", "));
Here 4 is the parallel threshold – when the map has at least 4 elements, the operation may run concurrently.
search()
Finds an entry that satisfies a predicate. Returns the first match.
String key = numbers.search(4, (k, v) -> v == 3 ? k : null);
System.out.println("Searched key: " + key);
reduce()
Aggregates values using a reducer. Useful for sums, products, or custom accumulations.
int sum = numbers.reduce(4, (k, v) -> v, (v1, v2) -> v1 + v2);
System.out.println("Sum of values: " + sum);
ConcurrentHashMap vs. HashMap
- Thread safety –
ConcurrentHashMapallows safe concurrent modifications;HashMapis not thread‑safe. - Bulk methods –
ConcurrentHashMapoffersforEach,search, andreducefor parallel processing.
Why Use ConcurrentHashMap?
- Supports high‑concurrency with minimal blocking.
- Internally divided into 16 segments, enabling up to 16 threads to modify different segments simultaneously.
- Operations like
putIfAbsentprevent accidental overwrites. - Built‑in synchronization eliminates the need for external locks.
Java
- Master Java Operators: Types, Syntax, & Practical Examples
- Mastering Java's super Keyword: Advanced Usage & Practical Examples
- Mastering Java Interfaces: Concepts, Implementation, and Best Practices
- Java List Interface: Overview, Implementations, and Key Methods
- Java TreeMap: Master Sorted Maps with Practical Examples
- Java HashSet Class: Complete Guide to Operations, Methods, and Set Theory
- Mastering Java TreeSet: Operations, Methods, and Practical Examples
- Mastering Java Collection Algorithms: Sorting, Shuffling, and More
- Generate Random Numbers in Java: Practical Guide with Random and Math.random
- Java Numbers Class – Wrapper Classes & Inheritance Explained