Home  >  Core Java

Java ConcurrentHashMap Example

By Arvind Rai, 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 the ConcurrentHashMap class.
1.
public ConcurrentHashMap() 
Ex.
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(); 
2.
public ConcurrentHashMap(int initialCapacity) 
initialCapacity : Initial size of map. A new empty map is created with the specified initial internal sizing. For the number of elements up to initialCapacity, there is no dynamic resize internally. Default initial capacity is 16.
Ex.
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(32); 
3.
public ConcurrentHashMap(Map<? extends K,? extends V> m) 
m : The specified map. A new map is created with elements of the specified map.
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); 
4.
public ConcurrentHashMap(int initialCapacity, float loadFactor) 
loadFactor : The load factor is the table density for establishing the initial table size. Default load factor is 0.75f.
Ex.
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(32, 0.70f); 
5.
public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) 
concurrencyLevel : The estimated number of concurrently updating threads. Default concurrency level is 16.
Ex.
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(32, 0.70f, 24); 

Add Elements

We can add elements in ConcurrentHashMap using following methods.
V put(K key, V value)
V putIfAbsent(K key, V value)
void putAll(Map<? extends K,? extends V> m) 
Find the example.
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);	
  }
} 
Output
{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, use forEach method.
void forEach(long parallelismThreshold,
   BiConsumer<? super K,? super V> action) 
Find the example.
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));
  }
} 
Output
Varanasi-20
Madurai-30
Kriskindha-40 

Compute

The ConcurrentHashMap 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) 
Find the example.
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
output: 31
{Mahesh=22, Nilesh=31} 

Reduce

The reduce 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) 
Find the example.
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
output: 31
{Mahesh=22, Nilesh=31} 

Search

Find the Java doc of search method.
<U> U 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. On success at any element, the processing is stopped for next elements.
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);
  }
} 
Output
22 

Replace

1.
V replace(K key, V value) 
Replaces the entry for a key only if currently mapped to some value.
2.
boolean replace(K key, V oldValue, V newValue) 
Replaces the oldValue with newValue for a key only if currently mapped to oldValue.
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);	
  }
} 
Output
Sohan
{20=Suresh, 10=Mohan, 30=Vishal}
isReplaced:true
{20=Suresh, 10=Mohan, 30=Vishnu} 

Remove

1.
V remove(Object key) 
Removes the key and its corresponding value from this map.
2.
boolean remove(Object key, Object value) 
Removes the entry for a key only if currently mapped to a given 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);	
  }
} 
Output
Sohan
{10=Mohan, 30=Vishal}
isRemoved:true
{10=Mohan} 

Get

1.
V get(Object key) 
Returns the value corresponding to key or null if there is no mapping for the key.
2.
V getOrDefault(Object key, V defaultValue) 
Returns the value corresponding to key. If there is no mapping for the key, then defaultValue is returned.
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
output: Sohan
output: Default value 

Reference

Java ConcurrentHashMap
POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us