A
ConcurrentHashMap
is a thread-safe version of aHashMap
that allows concurrent read and thread-safe update operations. Internally, it uses a Hashtable. TheConcurrentHashMap
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, likeput()
andremove()
. In that case, the result of theget()
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.
public int size()
This method doesn’t take any parameters.
This method returns an integer value that represents the number of mappings present in the map
object.
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());}}
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
.