The isEmpty() method in Java’s ConcurrentHashMap class is used to check whether the map is empty or not. It has the following signature:
boolean isEmpty()
The isEmpty() method works in a concurrent environment, which means that it can be called from multiple threads without causing any data race or synchronization issues.
When an isEmpty() operation is performed, the method first acquires the lock on all the segments of the map and then checks whether the map is empty or not.
Here is an example of using the isEmpty() method:
Java
import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); boolean result = map.isEmpty(); System.out.println( "Is the map empty? " + result); // true map.put( "Alice" , 25 ); result = map.isEmpty(); System.out.println( "Is the map empty? " + result); // false } } |
Is the map empty? true Is the map empty? false
The isEmpty() method of java.util.concurrent.ConcurrentHashMap is an in-built function in Java that checks if this map contains any key-value mappings and returns a boolean value.
Syntax:
public boolean isEmpty()
Return Value: The function returns a boolean value. It returns true if the ConcurrentHashMap is empty and returns false otherwise. The below programs illustrate the use of isEmpty() method:
Program 1: In this program the ConcurrentHashMap is non-empty.
Java
// Java Program Demonstrate isEmpty() // method of ConcurrentHashMap */ import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>(); chm.put( 100 , "Geeks" ); chm.put( 101 , "for" ); chm.put( 102 , "Geeks" ); // Checking for the emptiness of Map if (chm.isEmpty()) { System.out.println( "The ConcurrentHashMap" + " is empty." ); } else { // Displaying the ConcurrentHashMap System.out.println( "The Mappings are: " + chm); } } } |
The Mappings are: {100=Geeks, 101=for, 102=Geeks}
Program 2:In this program the ConcurrentHashMap is non-empty.
Java
// Java Program Demonstrate isEmpty() // method of ConcurrentHashMap */ import java.util.concurrent.*; class GFG { public static void main(String[] args) { ConcurrentHashMap chm = new ConcurrentHashMap(); // Checking for the emptiness of Map if (chm.isEmpty()) { System.out.println( "The ConcurrentHashMap" + " is empty." ); } else { // Displaying the ConcurrentHashMap System.out.println( "The Mappings are: " + chm); } } } |
Reference : https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#isEmpty()