ConcurrentHashMap is a Map implementation like HashMap and Hashtable, with additional support for concurrency features: Unlike Hastable or synchronizedMap which locks the entire map exclusively to gain thread-safety feature, ConcurrentHashMap allows concurrent writer and reader threads.

That means it allows some threads to modify the map and other threads to read values from the map at the same time, while Hashtable or synchronizedMap allows only one thread to work on the map at a time.
More specifically, ConcurrentHashMap allows any number of concurrent reader threads and a limited number of concurrent writer threads, and both reader and writer threads can operate on the map simultaneously. For more additional info Java Online Course
Reader threads perform retrieval operations such as get, containsKey, size, isEmpty, and iterate over keys set of the map.
Writer threads perform update operations such as put and remove. Iterators returned by ConcurrentHashMap are weakly consistent, meaning that the iterator may not reflect latest update since it was constructed.
An iterator should be used by only one thread and no ConcurrentModificationException
will be thrown if the map is modified while the iterator is being used.
ConcurrentHashMap is an implementation of ConcurrentMap which is a subtype of the Map interface.
A ConcurrentMap defines the following atomic operations:
- putIfAbsent(K key, V value): associates the specified key to the specified value if the key is not already associated with a value. This method is performed atomically, meaning that no other threads can intervene in the middle of checking absence and association.
- remove(Object key, Object value): removes the entry for a key only if currently mapped to some value. This method is performed atomically.
- replace(K key, V value): replaces the entry for a key only if currently mapped to some value. This method is performed atomically.
- replace(K key, V oldValue, V newValue): replaces the entry for a key only if currently mapped to a given value. This method is performed atomically.
Also note that the methods size() and isEmpty() may return an approximation instead of an exact count due to the concurrent nature of the map. ConcurrentHashMap does not allow null key and null value. Learn more skills from Java Online Training
ConcurrentHashMap has such advanced concurrent capabilities because it uses a finer-grained locking mechanism. We don’t delve in to the details of the locking algorithm, but understand that the ConcurrentHashMap uses different locks to lock different parts of the map, which enables concurrent reads and updates.
The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. In particular:
- Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
- Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService.
- Actions taken by the asynchronous computation represented by a Future happen-before actions subsequent to the retrieval of the result via Future.get() in another thread.
- Actions prior to “releasing” synchronizer methods such as Lock.unlock, Semaphore.release, and CountDownLatch.countDown happen-before actions subsequent to a successful “acquiring” method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await on the same synchronizer object in another thread.
- For each pair of threads that successfully exchange objects via an Exchanger, actions prior to the exchange() in each thread happen-before those subsequent to the corresponding exchange() in another thread.
- Actions prior to calling CyclicBarrier.await and Phaser.awaitAdvance (as well as its variants) happen-before actions performed by the barrier action, and actions performed by the barrier action happen-before actions subsequent to a successful return from the corresponding await in other threads.
Java ConcurrentHashMap Example:
The following example demonstrates how ConcurrentHashMap is used in a multi-threaded context. The program creates two writer threads and 5 reader threads working on a shared instance of a ConcurrentHashMap.
Example:
public class WriterThread extends Thread {
private ConcurrentMap<Integer, String> map;
private Random random;
private String name;
public WriterThread(ConcurrentMap<Integer, String> map,
String threadName, long randomSeed) {
this.map = map;
this.random = new Random(randomSeed);
this.name = threadName;
}
public void run() {
while (true) {
Integer key = random.nextInt(10);
String value = name;
if(map.putIfAbsent(key, value) == null) {
long time = System.currentTimeMillis();
String output = String.format("%d: %s has put [%d => %s]",
time, name, key, value);
System.out.println(output);
}
Integer keyToRemove = random.nextInt(10);
if (map.remove(keyToRemove, value)) {
long time = System.currentTimeMillis();
String output = String.format("%d: %s has removed [%d => %s]",
time, name, keyToRemove, value);
System.out.println(output);
}
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
To get in-depth knowledge, enroll for a live free demo on Learn Java Online