Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A HashMap is similar to a HashTable, which maps a key to its value and stores it for future reference. The only difference is that HashMap is not synchronised or thread-safe. For example, if a thread attempts to modify the contents of a HashMap object that is currently being iterated by another thread, it will throw a ConcurrentModificationException. This exception can be avoided by using the ConcurrentHashMap class instead of HashMap.
ConcurrentHashMap supports full concurrency of retrieval and updates despite having the exact functional specifications as HashMap. It implements the ConcurrentMap interface that is capable of synchronising all concurrent activities related to it without affecting the consistency of entries in the map.
ConcurrentHashMap is an enhanced version of the HashMap that deals with concurrent thread operations.
Unlike the HashMap, it is synchronised and does not accept null as a key or value.
The default concurrency level of a ConcurrenHashMap is 16. This means that a maximum of 16 threads can modify the map contents simultaneously. However, any number of threads can read the map at the same time.
All objects, by default, can be divided into 16 segments based on the concurrency level. ConcurrentHashMaps implement a Segment/Bucket locking mechanism in which a thread locks a segment in the object it wants to operate on.
It supports sequential and parallel bulk operations even to maps that are simultaneously modified by multiple threads.
Constructors of Java ConcurrentHashMap
Three important parameters are involved with the constructors of this class.
Concurrency level: It specifies the number of threads that would concurrently update the map.
Load factor: It is a threshold factor used for control resizing.
Initial capacity: It defines the number of entries the map can hold initially.
The ConcurrentHashMap has five constructors:
ConcurrentHashMap() -
It creates a new, empty map with default concurrency level (16), load factor (0.75) and initial capacity (16).
ConcurrentHashMap<String, Integer> evenNumbers = new ConcurrentHashMap<>();
You can also try this code with Online Java Compiler
It gives the accumulation of the given transformations of all entries using a specified reducer to combine values.
reduceEntries(long parallelismThreshold, reducer)
Map.Entry<K, V>
It gives the accumulation of all entries using a specified reducer to combine values.
reduceEntriesToDouble
reduceEntriesToInt
reduceEntriesToLong
double
It gives the accumulation of the given transformations of all entries using a specified reducer to combine values and the given basis as an identity value.
Parameter: long parallelismThreshold, transformer, data_type basis, reducer
It gives the accumulation of the given transformations of all keys using a specified reducer to combine values.
reduceKeys(long parallelismThreshold, reducer)
K
It gives the accumulation of all keys using a specified reducer to combine values.
reduceKeysToDouble
reduceKeysToInt
reduceKeysToLong
double
It gives the accumulation of the given transformations of all keys using a specified reducer to combine values and the given basis as an identity value.
Parameter: long parallelismThreshold, transformer, data_type basis, reducer
It gives the accumulation of the given transformations of all key-value pairs using a specified reducer to combine values.
reduceToDouble
reduceToInt
reduceToLong
double
It gives the accumulation of the given transformations of all key-value pairs using a specified reducer to combine values and the given basis as an identity value.
Parameters: long parallelismThreshold, transformer, data_type basis, reducer
It gives the accumulation of the given transformations of all values using a specified reducer to combine values.
reduceValues(long parallelismThreshold, reducer)
V
It gives the accumulation of all values using a specified reducer to combine values.
reduceValuesToDouble
reduceValuesToInt
reduceValuesToLong
double
It gives the accumulation of the given transformations of all values using a specified reducer to combine values and the given basis as an identity value.
Parameter: long parallelismThreshold, transformer, data_type basis, reducer
int
long
search( long parallelismThreshold, searchFunction)
<U> U
(U - the return type of the search function)
It returns a non-null result from applying the given search function on each (key, value)
searchEntries()
It returns a non-null result from applying the given search function on each entry, key or value.
Parameters: long parallelismThreshold, searchFunction
searchKeys()
searchValues()
forEach(action)
void
It performs a given action for each key-value pair.
Optional parameters: long parallelismThreshold, transformer
forEachEntry(action)
void
It performs a given action for each entry, key or value.
Optional parameters: long parallelismThreshold, transformer
forEachKey(action)
forEachValue(action)
Description of parameters:
ParallelismThreshold is the estimated number of elements needed for an operation to be executed in parallel.
Transformer is a function that returns the transformation of an element.
Basis defines the initial default value for the reducer.
Reducer is a commutative and associative combining function.
Basic operations of ConcurrentHashMap in Java
1. Adding elements
put(), putAll() and putIfAbsent() methods are used to add elements into the map.
import java.util.concurrent.ConcurrentHashMap;
class AddElement
{
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> evenNumbers = new ConcurrentHashMap<>();
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
System.out.println("ConcurrentHashMap of even numbers: " + evenNumbers);
ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
numbers.put("One", 1);
numbers.putAll(evenNumbers);
numbers.putIfAbsent("Three", 3);
System.out.println("ConcurrentHashMap of numbers: " + numbers);
}
}
You can also try this code with Online Java Compiler
ConcurrentHashMap of even numbers: {Four=4, Two=2}
ConcurrentHashMap of numbers: {One=1, Four=4, Two=2, Three=3}
2. Removing elements
remove() is used to remove elements from the map.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveElement
{
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> evenNumbers = new ConcurrentHashMap<>();
evenNumbers.put("One", 1);
evenNumbers.put("Two", 2);
evenNumbers.put("Three", 3);
evenNumbers.put("Four", 4);
System.out.println("ConcurrentHashMap of numbers: " + evenNumbers);
evenNumbers.remove("One");
// Using remove() on a key-value pair
evenNumbers.remove("Three",3);
// Using remove() on a key that has a different value
evenNumbers.remove("four",2);
System.out.println("ConcurrentHashMap of even numbers: " + evenNumbers);
}
}
You can also try this code with Online Java Compiler
ConcurrentHashMap of numbers: {One=1, Four=4, Two=2, Three=3}
ConcurrentHashMap of even numbers: {Four=4, Two=2}
3. Accessing elements
entrySet(), values(), keys(), keySet() and elements() are used to access a set of elements all together.
get(), getOrDefault() are used to obtain values of specified keys.
import java.util.concurrent.ConcurrentHashMap;
public class AccessElement
{
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
numbers.put("Four", 4);
System.out.println("ConcurrentHashMap Entries: " + numbers.entrySet());
// Using keys() that returns an enumeration object
Enumeration enum_keys= numbers.keys();
System.out.print("ConcurrentHashMap Keys: ");
while(enum_keys.hasMoreElements())
System.out.print(enum_keys.nextElement() + " ");
System.out.println();
System.out.println("ConcurrentHashMap Values: " + numbers.values());
System.out.println("Value of One is " + numbers.get("One"));
// Using getOrDefault() where default value is set to -1
System.out.println("Value of Five is " + numbers.getOrDefault("Five",-1));
}
}
You can also try this code with Online Java Compiler
ConcurrentHashMap Entries: [One=1, Four=4, Two=2, Three=3]
ConcurrentHashMap Keys: One Four Two Three
ConcurrentHashMap Values: [1, 4, 2, 3]
Value of One is 1
Value of Five is -1
Traversal - The iterator interface is used to traverse an Identity hash map. The next() method is used to print the consecutive elements of the map.
import java.util.concurrent.ConcurrentHashMap;
public class Traverse
{
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
numbers.put("Four", 4);
// Using entrySet()
Iterator<ConcurrentHashMap.Entry<String, Integer> >
itr = numbers.entrySet().iterator();
// The hasNext() method checks if there is a next element
while (itr.hasNext()) {
ConcurrentHashMap.Entry<String, Integer> entry = itr.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
}
You can also try this code with Online Java Compiler
An iterator is a cursor used to retrieve or remove elements one by one. They are universal and can be applied to any collection object. Iterator objects are created using the iterator() method present in the collection interface.
Enumerations are used to get elements from legacy collections like Vectors, HashTable. Like an iterator, it is a cursor used to read or retrieve elements. However, it cannot remove elements.
What are the differences between ConcurrentHashMap and HashTable?
ConcurrentHashMap uses a multiple segment/bucket lock mechanism at the object level, while HashTable uses a single lock for the whole data.
ConcurrentHashMap uses a fail-safe iterator, and HashTable uses an enumerator to iterate the values of their objects.
ConcurrentHashMap is faster and has a better performance compared to the HashTable as it experiences synchronisation overhead.
Conclusion
The applications and programs built today are expected to have high efficiency and performance while executing concurrent tasks. Maps, hash tables and related interfaces involve multiple threads accessing and modifying their objects concurrently. In such situations, ConcurrentMaps and ConcurrentHashmaps play an essential role. This blog explains the features of ConcurrentHashMaps in detail. It also discusses the various methods provided by this class to perform basic and bulky operations.