What is a ConcurrentHashMap in Java?

A ConcurrentHashMap is a modified version of a HashMap that was made to accommodate concurrent operations. It uses a hash table to store data in the form of key-value pairs.

svg viewer

Retrieval

Retrieval operations do not lock the table containing the data, which leads to them being overlapped with update operations (e.g., put, remove, etc.). In case of an overlap, a retrieval operation will not wait for an update operation to complete. For example, if get("key") finishes while put("key", 10) is in progress, get("key") will return the previous value associated with the key instead of 10.

Update

A ConcurrentHashMap allows concurrent updates to the table. The number of threads that can update (or modify) the table, without contention, can be specified as the third parameter of an overloaded constructor:

// An overloaded constructor of ConcurrentHashMap:
ConcurrentHashMap<K, V>(int initialCapacity, float loadFactor, int concurrencyLevel)

Constructor parameters

  1. initialCapacity: The initial size of the hash table used by the ConcurrentHashMap (default value is 16).
  2. loadFactor: The percentage of the hash table which is filled before its size is doubled (default value is 0.75).
  3. concurrencyLevel: The number of updates which can be performed on the hash table without contention. A low value will make contention occur more frequently, whereas a high value will take up more space and time (default value is 16).

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved