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

Overview

The isEmpty() method of ConcurrentHashMap is used to check if the specified ConcurrentHashMap object is empty.

ConcurrentHashMap is a thread-safe version of a HashMap that allows concurrent read and thread-safe update operations. Internally, it uses a Hashtable. The ConcurrentHashMap object is divided into multiple portions according to the concurrency level. During an update operation, only a specific portion of the map is locked instead of the whole map being locked. Read more here.

Syntax

public boolean isEmpty()

Parameters

This method doesn’t take any argument(s).

Return value

This method returns True if the map doesn’t have any mappings. Otherwise, it returns False.

Code

The following example demonstrates how to use the isEmpty() method.

import java.util.concurrent.ConcurrentHashMap;
class ConcurrentHashMapisEmptyExample {
public static void main( String args[] ) {
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
System.out.println("\nChecking if ConcurrentHashMap is empty : "+ map.isEmpty());
map.put(1, "one");
map.put(2, "two");
System.out.println("\nAfter Adding some mappings to the map");
System.out.println("\nChecking if ConcurrentHashMap is empty : "+ map.isEmpty());
}
}

Code explanation

In the code written above:

  • In line 1, we import the ConcurrentHashMap class.

  • In line 4, we create a ConcurrentHashMap object with the name map.

  • In line 5, we use the isEmpty() method to check if the map is empty. We get True as a result because the map object is empty.

  • In lines 6 and 7, we use the put() method to add two mappings ({1=one, 2=two}) to the map object.

  • In line 9, we use the isEmpty() method to check if the map is empty. We get False as a result because the map object is not empty.

Free Resources