Java ConcurrentHashMap Example
February 17, 2022
On this page we will learn Java ConcurrentHashMap
class.
1. The
ConcurrentHashMap
is a hash table that supports full concurrency of retrievals and high expected concurrency for updates.
2. The
ConcurrentHashMap
has the same functional specification as Hashtable
class. The ConcurrentHashMap
has all equivalent methods of Hashtable
class.
3. All operations of
ConcurrentHashMap
are thread safe except retrieval. Retrieval operations do not entail locking.
4. In case of update and retrieval operation overlapping, the retrieval request retrieves data just after completion of currently executing put, remove or update operations. This is called happens-before relation between update and retrieval operations.
5. In the aggregate operations such as
putAll
and clear
, the concurrent retrievals may reflect insertion or removal of only some entries. This is because the retrieval operation may be taking place before completion of putAll
and clear
operations. The Iterators
, Spliterators
and Enumerations
also return elements reflecting the state of ConcurrentHashMap
at some point.
6. The
ConcurrentHashMap
does not allow null to be used as a key or value. It behaves like Hashtable
but unlike HashMap
. The Hashtable
does not allow null whereas HashMap
allows null.
7. The
ConcurrentHashMap
supports a set of sequential and parallel bulk operations. The elements of a ConcurrentHashMap
are not ordered in any particular way and may be processed in different orders in different parallel executions.
8. The bulk operations of
ConcurrentHashMap
such as forEach
, search
, reduce
methods accept a parallelismThreshold
argument. These bulk methods can proceed either sequentially or parallel on the basis of specified parallelismThreshold
. These methods proceed sequentially if the current map size is estimated to be less than the specified parallelismThreshold
. If we pass Long.MAX_VALUE, there will be no parallelism ever and if we pass 1, there will be maximum parallelism.
Initialize ConcurrentHashMap
Find the constructors to initialize theConcurrentHashMap
class.
1.
public ConcurrentHashMap()
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
public ConcurrentHashMap(int initialCapacity)
Ex.
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(32);
public ConcurrentHashMap(Map<? extends K,? extends V> m)
Ex.
Map<Integer, String> hashMap = new HashMap<>(); hashMap.put(10, "Mohan"); hashMap.put(20, "Sohan"); hashMap.put(30, "Vishal"); ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(hashMap);
public ConcurrentHashMap(int initialCapacity, float loadFactor)
Ex.
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(32, 0.70f);
public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)
Ex.
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(32, 0.70f, 24);
Add Elements
We can add elements inConcurrentHashMap
using following methods.
V put(K key, V value) V putIfAbsent(K key, V value) void putAll(Map<? extends K,? extends V> m)
AddElements.java
package com.concretepage; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class AddElements { public static void main(String[] args) { // Example -1 ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("Mohan", 20); map.put("Sohan", 22); map.put("Vishal", 25); System.out.println(map); // Example -2 map.putIfAbsent("Vishal", 28); map.putIfAbsent("Suresh", 30); System.out.println(map); // Example -3 Map<String, Integer> hashMap = new HashMap<>(); map.put("Kishore", 32); map.put("Nilesh", 34); map.putAll(hashMap); System.out.println(map); } }
{Mohan=20, Sohan=22, Vishal=25} {Mohan=20, Suresh=30, Sohan=22, Vishal=25} {Mohan=20, Suresh=30, Kishore=32, Sohan=22, Vishal=25, Nilesh=34}
Iterate Elements
To iterate elements, useforEach
method.
void forEach(long parallelismThreshold, BiConsumer<? super K,? super V> action)
ForEach.java
package com.concretepage; import java.util.concurrent.ConcurrentHashMap; public class ForEach { public static void main(String[] args) { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("Varanasi", 20); map.put("Madurai", 30); map.put("Kriskindha", 40); map.forEach(1, (k, v) -> System.out.println(k + "-" + v)); } }
Varanasi-20 Madurai-30 Kriskindha-40
Compute
TheConcurrentHashMap
provides compute
method that computes the value for the specified key. It updates the value with new computed value corresponding to specified key.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
Compute.java
package com.concretepage; import java.util.concurrent.ConcurrentHashMap; public class Compute { public static void main(String[] args) { ConcurrentHashMap<String, Integer> conMap = new ConcurrentHashMap<>(); conMap.put("Mahesh", 22); conMap.put("Nilesh", 25); Integer output = conMap.compute("Nilesh", (k, v) -> k.length() + v); System.out.println("output: " + output); System.out.println(conMap); } }
output: 31 {Mahesh=22, Nilesh=31}
Reduce
Thereduce
method returns the result of accumulating the given transformation of all key/value pairs using the given reducer to combine values, or null if none.
<U> U reduce(long parallelismThreshold, BiFunction<? super K,? super V,? extends U> transformer, BiFunction<? super U,? super U,? extends U> reducer)
Reduce.java
package com.concretepage; import java.util.concurrent.ConcurrentHashMap; public class Reduce { public static void main(String[] args) { ConcurrentHashMap<String, Integer> conMap = new ConcurrentHashMap<>(); conMap.put("Mahesh", 22); conMap.put("Nilesh", 25); Integer output = conMap.compute("Nilesh", (k, v) -> k.length() + v); System.out.println("output: " + output); System.out.println(conMap); } }
output: 31 {Mahesh=22, Nilesh=31}
Search
Find the Java doc ofsearch
method.
<U> U search(long parallelismThreshold, BiFunction<? super K,? super V,? extends U> searchFunction)
Search.java
package com.concretepage; import java.util.concurrent.ConcurrentHashMap; public class Search { public static void main(String[] args) { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("Mohan", 20); map.put("Sohan", 22); map.put("Vishal", 25); Integer output = map.search(1, (k, v) -> k.startsWith("S") ? v : null); System.out.println(output); } }
22
Replace
1.V replace(K key, V value)
2.
boolean replace(K key, V oldValue, V newValue)
Replace.java
package com.concretepage; import java.util.concurrent.ConcurrentHashMap; public class Replace { public static void main(String[] args) { ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(); map.put(10, "Mohan"); map.put(20, "Sohan"); map.put(30, "Vishal"); //Example -1 String output = map.replace(20, "Suresh"); System.out.println(output); System.out.println(map); //Example -2 Boolean isReplaced = map.replace(30, "Vishal", "Vishnu"); System.out.println("isReplaced:" + isReplaced); System.out.println(map); } }
Sohan {20=Suresh, 10=Mohan, 30=Vishal} isReplaced:true {20=Suresh, 10=Mohan, 30=Vishnu}
Remove
1.V remove(Object key)
2.
boolean remove(Object key, Object value)
Remove.java
package com.concretepage; import java.util.concurrent.ConcurrentHashMap; public class Remove { public static void main(String[] args) { ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(); map.put(10, "Mohan"); map.put(20, "Sohan"); map.put(30, "Vishal"); //Example -1 String output = map.remove(20); System.out.println(output); System.out.println(map); //Example -2 Boolean isRemoved = map.remove(30, "Vishal"); System.out.println("isRemoved:" + isRemoved); System.out.println(map); } }
Sohan {10=Mohan, 30=Vishal} isRemoved:true {10=Mohan}
Get
1.V get(Object key)
2.
V getOrDefault(Object key, V defaultValue)
Get.java
package com.concretepage; import java.util.concurrent.ConcurrentHashMap; public class Get { public static void main(String[] args) { ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(); map.put(10, "Mohan"); map.put(20, "Sohan"); map.put(30, "Vishal"); //Example -1 String output = map.get(20); System.out.println("output: " + output); //Example -2 output = map.getOrDefault(40, "Default value"); System.out.println("output: " + output); } }
output: Sohan output: Default value