ConcurrentHashMap is a thread-safe implementation of the Map interface that allows multiple threads to access and modify the map concurrently without locking the entire map. It is part of the java.util.concurrent package and provides better performance than synchronized collections such as Hashtable in multi-threaded applications.
- Uses fine-grained synchronization and CAS (Compare-And-Swap) operations (Java 8+).
- Does not allow null keys or null values.
- Iterators are weakly consistent and do not throw ConcurrentModificationException.
import java.util.concurrent.ConcurrentHashMap;
public class GFG {
public static void main(String[] args)
{
ConcurrentHashMap<Integer, String> map
= new ConcurrentHashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Mango");
System.out.println(map);
}
}
Output
{1=Apple, 2=Banana, 3=Mango}
Explanation: In this example, a ConcurrentHashMap is created and populated using the put() method. The map stores key-value pairs and prints all the entries.
Internal Working (Java 8+)
Before Java 8, ConcurrentHashMap used segment-based locking, where the map was divided into multiple segments.
From Java 8 onwards, it uses:
- CAS (Compare-And-Swap) for atomic updates.
- Fine-grained synchronization only when required.
- Node arrays and buckets, similar to HashMap.
This design improves scalability and performance in highly concurrent environments.
ConcurrentHashMap Hierarchy
It implements Serializable, ConcurrentMap<K,â V>, Map<K,â V> interfaces and extends AbstractMap<K, âV> class.

Declaration of ConcurrentHashMap
In Java, the declaration of ConcurrentHashMap can be done as:
ConcurrentHashMap<KeyType, ValueType> map = new ConcurrentHashMap<>();
Where
- KeyType -> Type of keys.
- ValueType -> Type of values.
Note: Here the KeyType is the type of the key in the map and ValueType is the type of values associated with the keys.
Constructors of ConcurrentHashMap
ConcurrentHashMap provides several constructors to create a map with different initial configurations such as capacity, load factor, and concurrency level.
1. ConcurrentHashMap(): Creates an empty ConcurrentHashMap with default initial capacity and settings.
Syntax:
ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
2. ConcurrentHashMap(int initialCapacity): Creates a ConcurrentHashMap with the specified initial capacity.
Syntax:
ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>(int initialCapacity);
3. ConcurrentHashMap(int initialCapacity, float loadFactor): Creates a ConcurrentHashMap with the specified initial capacity and load factor.
Syntax:
ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>(int initialCapacity, float loadFactor);
4. ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel): Creates a ConcurrentHashMap with specified initial capacity, load factor, and estimated number of concurrently updating threads.
Syntax:
ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>(int initialCapacity, float loadFactor, int concurrencyLevel);
5. ConcurrentHashMap(Map<? extends K, ? extends V> m): Creates a ConcurrentHashMap containing all mappings from the specified map.
Syntax:
ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>(Map m);
Example: This example demonstrates the usage of various ConcurrentHashMap methods.
import java.util.concurrent.*;
class Geeks {
public static void main(String[] args)
{
// create an instance of
// ConcurrentHashMap
ConcurrentHashMap<Integer, String> m
= new ConcurrentHashMap<>();
// Insert mappings using
// put method
m.put(100, "Hello");
m.put(101, "Geeks");
m.put(102, "Geeks");
// Here we cant add Hello because 101 key
// is already present in ConcurrentHashMap object
m.putIfAbsent(101, "Hello");
// We can remove entry because 101 key
// is associated with For value
m.remove(101, "Geeks");
// Now we can add Hello
m.putIfAbsent(103, "Hello");
// We cant replace Hello with For
m.replace(101, "Hello", "For");
System.out.println(m);
}
}
Output
{100=Hello, 102=Geeks, 103=Hello}
Common Operations on ConcurrentHashMap
1. Adding Elements
We can use put() or putAll() to insert element to a ConcurrentHashMap.
import java.util.concurrent.*;
public class Geeks{
public static void main(String[] args) {
// Create ConcurrentHashMap
ConcurrentHashMap<String, String> map1 = new ConcurrentHashMap<>();
// Add elements to map
map1.put("1", "One");
map1.put("2", "Two");
map1.put("3", "Three");
map1.put("4", "Four");
map1.put("5", "Five");
map1.put("6", "Six");
// Print map1
System.out.println("map1: " + map1);
// Create a new map and copy all entries from map1
ConcurrentHashMap<String, String> map2 = new ConcurrentHashMap<>(map1);
// Print map2
System.out.println("map2: " + map2);
}
}
Output
map1: {1=One, 2=Two, 3=Three, 4=Four, 5=Five, 6=Six}
map2: {1=One, 2=Two, 3=Three, 4=Four, 5=Five, 6=Six}
2. Removing Elements
We can use the remove() method to remove elements from the ConcurrentHashMap. To clear the entire map, we can use the clear().
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class Geeks{
public static void main(String[] args)
{
// Creating ConcurrentHashMap
Map<String, String> m
= new ConcurrentHashMap<String, String>();
// Adding elements to the map
// using put() method
m.put("1", "One");
m.put("2", "Two");
m.put("3", "Three");
m.put("4", "Four");
m.put("5", "Five");
m.put("6", "Six");
System.out.println("Map: " + m);
System.out.println();
// Removing the mapping
// with existing key 6
// using remove() method
String s = m.remove("6");
// Printing the map after remove()
System.out.println(
"After removing mapping with key 6:");
System.out.println("Map: " + m);
System.out.println("Value removed: "
+ s);
System.out.println();
// Removing the mapping
// with non-existing key 10
// using remove() method
s = m.remove("10");
// Printing the map after remove()
System.out.println(
"After removing mapping with key 10:");
System.out.println("Map: " + m);
System.out.println("Value removed: "
+ s);
System.out.println();
// Now clear the map using clear()
m.clear();
System.out.println("Map after use of clear(): "
+ m);
}
}
Output:

3. Accessing Elements
We can use the  get() method to access the elements of the ConcurrentHashMap.
import java.util.concurrent.*;
class Geeks {
public static void main(String[] args)
{
// create an instance of ConcurrentHashMap
ConcurrentHashMap<Integer, String> m
= new ConcurrentHashMap<Integer, String>();
// insert mappings using put method
m.put(100, "Geeks");
m.put(101, "for");
m.put(102, "Geeks");
m.put(103, "Contribute");
// Displaying the HashMap
System.out.println("ConcurrentHashMap:" + m);
// Display the value of 100
System.out.println("The Value associated to "
+ "100 is : " + m.get(100));
// Getting the value of 103
System.out.println("The Value associated to "
+ "103 is : " + m.get(103));
}
}
Output
ConcurrentHashMap:{100=Geeks, 101=for, 102=Geeks, 103=Contribute}
The Value associated to 100 is : Geeks
The Value associated to 103 is : Contribute
4. Iterating Elements
We can use the Iterator interface to traverse over the elements of ConcurrentHashMap.
import java.util.*;
import java.util.concurrent.*;
public class Geeks {
public static void main(String[] args)
{
// create an instance of ConcurrentHashMap
ConcurrentHashMap<Integer, String> m
= new ConcurrentHashMap<Integer, String>();
// Add elements using put()
m.put(8, "Third");
m.put(6, "Second");
m.put(3, "First");
m.put(11, "Fourth");
// Create an Iterator over the
// ConcurrentHashMap
Iterator<Map.Entry<Integer, String>> i = m.entrySet().iterator();
i = m.entrySet().iterator();
// The hasNext() method is used to check if there is
// a next element The next() method is used to
// retrieve the next element
while (i.hasNext()) {
ConcurrentHashMap.Entry<Integer, String> entry
= i.next();
System.out.println("Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
}
}
Output
Key = 3, Value = First Key = 6, Value = Second Key = 8, Value = Third Key = 11, Value = Fourth
Methods of ConcurrentHashMap
Methods | Description |
|---|---|
| clear() | Removes all of the mappings from this map. |
| computeâ(K key, BiFunction<? super K,â? super V,â? extends V> remappingFunction) | Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
| computeIfAbsentâ(K key, Function<? super K,â? extends V> mappingFunction) | If the specified key is not already associated with a value, attempts to compute its value using the given mapping function and enters it into this map unless null. |
| computeIfPresentâ(K key, BiFunction<? super K,â? super V,â? extends V> remappingFunction) | If the value for the specified key is present, attempts to compute a new mapping given the key and its current mapped value. |
| containsâ(Object value) | Tests if some keymaps into the specified value in this table. |
| containsKeyâ(Object key) | Tests if the specified object is a key in this table. |
| containsValueâ(Object value) | Returns true if this map maps one or more keys to the specified value. |
| elements() | Returns an enumeration of the values in this table. |
| entrySet() | Returns a Set view of the mappings contained in this map. |
| equalsâ(Object o) | Compares the specified object with this map for equality. |
| getâ(Object key) | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
| getOrDefaultâ(Object key, V defaultValue) | Returns the value to which the specified key is mapped, or the given default value if this map contains no mapping for the key. |
| hashCode() | Returns the hash code value for this Map, i.e., the sum of, for each key-value pair in the map, key.hashCode() ^ value.hashCode(). |
| Â keys() | Returns an enumeration of the keys in this table. |
| keySet() | Returns a Set view of the keys contained in this map. |
| mappingCount() | Returns the number of mappings. |
| mergeâ(K key, V value, BiFunction<? super V,â? super V,â? extends V> remappingFunction) | If the specified key is not already associated with a (non-null) value, associates it with the given value. |
| newKeySet() | Creates a new Set backed by a ConcurrentHashMap from the given type to Boolean.TRUE. |
| newKeySetâ(int initialCapacity) | Creates a new Set backed by a ConcurrentHashMap from the given type to Boolean.TRUE. |
| putâ(K key, V value) | Maps the specified key to the specified value in this table. |
| putAllâ(Map<? extends K,â? extends V> m) | Copies all of the mappings from the specified map to this one. |
| putIfAbsentâ(K key, V value) | If the specified key is not already associated with a value, associates it with the given value. |
| removeâ(Object key) | Removes the key (and its corresponding value) from this map. |
| removeâ(Object key, Object value) | Removes the entry for a key only if currently mapped to a given value. |
| replaceâ(K key, V value) | Replaces the entry for a key only if currently mapped to some value. |
| replaceâ(K key, V oldValue, V newValue) | Replaces the entry for a key only if currently mapped to a given value. |
| searchâ(long parallelismThreshold, BiFunction<? super K,â? super V,â? extends U> searchFunction) | Returns a non-null result from applying the given search function on each (key, value), or null if none. |
| searchEntriesâ(long parallelismThreshold, Function<Map.Entry<K,âV>,â? extends U> searchFunction) | Returns a non-null result from applying the given search function on each entry, or null if none. |
| searchKeysâ(long parallelismThreshold, Function<? super K,â? extends U> searchFunction) | Returns a non-null result from applying the given search function on each key, or null if none. |
| searchValuesâ(long parallelismThreshold, Function<? super V,â? extends U> searchFunction) | Returns a non-null result from applying the given search function on each value, or null if none. |
| toString() | Returns a string representation of this map. |
| values() | Returns a Collection view of the values contained in this map. |
Methods Declared in Class java.util.AbstractMap
Method | Description |
|---|---|
| clone() | Returns a shallow copy of this AbstractMap instance: the keys and values themselves are not cloned. |
| isEmpty() | Returns true if this map contains no key-value mappings. |
| size() | Returns the number of key-value mappings in this map. |
Methods Declared in Interface java.util.concurrent.ConcurrentMap
Method | Description |
|---|---|
| forEachâ(BiConsumer<? super K,â? super V> action) | Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. |
| replaceAllâ(BiFunction<? super K,â? super V,â? extends V> function) | Replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |