What is the ConcurrentHashMap.clear() method in Java?
A
ConcurrentHashMapis a thread-safe version of a HashMap that allows concurrent read and thread-safe update operation. Internally, it usesHashtable.
- The
ConcurrentHashMapobject is divided into multiple portions according to the concurrency level, so during an update operation, only a specific portion of theMapis locked, instead of locking the wholeMap.- Since it doesn’t lock the whole
Map, there may be a chance of read overlapping with update operations likeput()andremove().- In that case, the result of the
get()method will reflect the most recently completed operation from their start.- Also,
nullis not allowed as a key or value.
The clear() method of the ConcurrentHashMap class removes all of the key-value mappings from a specified ConcurrentHashMap object. After calling this method, the ConcurrentHashMap object becomes empty.
Syntax
public void clear()
This method doesn’t take any parameters and does not return a value.
Code
The code below shows how to use the clear() method.
import java.util.concurrent.ConcurrentHashMap;class Clear {public static void main( String args[] ) {ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();map.put(1, "one");map.put(2, "two");System.out.println("map is : "+ map);map.clear();System.out.println("\nAfter Calling Clear method");System.out.println("\nmap is : " + map);}}
Explanation
In the code above:
-
Line 1: We import the
ConcurrentHashMapclass. -
Lines 5-8: We create a
ConcurrentHashMapobject and use theput()method to add two mappings ({1=one, 2=two}) tomap. -
Line 11: We use the
clear()method to remove all the mappings frommap. This makesmapempty. -
Line 14: We print
mapto ensure that it is empty.