What is the ConcurrentHashMap.size() method in Java?
Overview
A
ConcurrentHashMapis a thread-safe version of aHashMapthat allows concurrent read and thread-safe update operations. Internally, it uses a Hashtable. TheConcurrentHashMapobject is divided into multiple portions according to the concurrency level. Hence, during an update operation, only a specific portion of the map is locked instead of the whole map. Since it doesn’t lock the whole map, there may be a chance of read operations overlapping with update operations, likeput()andremove(). In that case, the result of theget()method will reflect the most recently completed operation. In this method,nullis not allowed as a key or value.
The size method can be used to get the number of mappings that are present in the ConcurrentHashMap object.
Syntax
public int size()
Parameters
This method doesn’t take any parameters.
Return value
This method returns an integer value that represents the number of mappings present in the map object.
Code
The code below demonstrates how to use the size method.
import java.util.concurrent.ConcurrentHashMap;class Size {public static void main( String args[] ) {ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();map.put(1, "one");map.put(2, "two");map.put(3, "three");System.out.println("The map is " + map);System.out.println("The size of the the map is " + map.size());}}
Code explanation
In the code above:
-
In line 1, we import the
ConcurrentHashMapclass. -
In line 4, we create a
ConcurrentHashMapobject with the namemap. -
From lines 5–7, we use the
put()method of themapobject to add three entries to themap. -
In line 10, we use the
size()method of themapobject to get the number of elements that are present in themap. In this case, our return value is3.