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

Overview

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. 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, like put() and remove(). In that case, the result of the get() method will reflect the most recently completed operation. In this method, null is 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 ConcurrentHashMap class.

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

  • From lines 5–7, we use the put() method of the map object to add three entries to the map.

  • In line 10, we use the size() method of the map object to get the number of elements that are present in the map. In this case, our return value is 3.

Free Resources