What is the ConcurrentHashMap.clear() method in Java?

ConcurrentHashMap is a thread-safe version of a HashMap that allows concurrent read and thread-safe update operation. Internally, it uses Hashtable.

  • The ConcurrentHashMap object is divided into multiple portions according to the concurrency level, so during an update operation, only a specific portion of the Map is locked, instead of locking the whole Map.
  • Since it doesn’t lock the whole Map, there may be a chance of read overlapping with update operations like put() and  remove().
  • In that case, the result of the get() method will reflect the most recently completed operation from their start.
  • Also, null is 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 ConcurrentHashMap class.

  • Lines 5-8: We create a ConcurrentHashMap object and use the put() method to add two mappings ({1=one, 2=two}) to map.

  • Line 11: We use the clear() method to remove all the mappings from map. This makes map empty.

  • Line 14: We print map to ensure that it is empty.

Free Resources