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.
A
ConcurrentHashMapis a thread-safe version of a HashMap that allows concurrent read and thread-safe update operations. Internally, it uses a Hashtable. TheConcurrentHashMapobject 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
ConcurrentHashMapclass. -
In line 4, we create a
ConcurrentHashMapobject with the namemap. -
In line 5, we use the
isEmpty()method to check if themapis empty. We getTrueas a result because themapobject is empty. -
In lines 6 and 7, we use the
put()method to add two mappings ({1=one, 2=two}) to themapobject. -
In line 9, we use the
isEmpty()method to check if themapis empty. We getFalseas a result because themapobject is not empty.