Top 10 Java ConcurrentHashMap Interview Questions and Answers

The ConcurrentHashMap class part of concurrent collections added on JDK 1.5 e.g. BlockingQueue, CopyOnWriteArrayList, CopyOnWriteArraySet etc. It is a replacement of synchronized hash-based map implementations e.g. Hashtable and synchronized HashMap. It implements Map and ConcurrentMap (a sub-interface of Map) interface which allows you to store key value pairs. The class is similar to HashMap or Hashtable but it's more scalable and the right fit for concurrent Java application. Unlike Hashtable which achieves its thread-safety by compromising scalability, ConcurrentHashMap uses advanced techniques e.g. dividing the map into segments to remain thread-safe and scalable at the same time.

Because of its performance and scalability as well as thread-safety, it is the most popular choice of Map in concurrent Java applications. In general, replacing synchronized collections with a concurrent collection can dramatically improve the scalability of your Java application with little risk, as advised on Java Concurrency in Practice.

Java ConcurrentHashMap Interview Questions with Answers

Here are some of the best and frequently asked Java ConcurrentHashMap interview questions. These questions are collected from the real interview, hence, don't be surprised if you have already seen them during interviews. These questions will not only help you to do well on interviews but also encourage you to learn more about the concurrent hash map, which will eventually help you in your day to day programming job.

What is ConcurrentHashMap in Java? (answer)
The java.util.concurrent.ConcurrentHashMap is a concurrent collection class added on JDK 1.5 as a replacement of synchronized hash-based map implementations e.g. Hashtable and synchronized HashMap. They offer better performance and scalability over their synchronized counterpart with little risk.

is ConcurrentHashMap thread-safe in Java? (answer)
Yes, ConcurrentHashMap is thread-safe in Java, which means two thread can modify the map without damaging its internal data structure e.g. array and linked list. If you compare this to HashMap, which is not thread-safe, exposing HashMap to multiple threads may damage internal data structure and may render the map completely useless, where many links may go missing or pointing to wrong elements.

How does ConcurrentHashMap achieve thread-safety? (answer)
The java.util.ConcurrentHashMap achieves thread-safety by dividing the map into segments and locking only the segment which requires instead of locking the whole map. So, yes, it achieves thread-safety using locking but it performs better because it never locks the whole map. This technique is also known as lock stripping.

Can multiple threads read from ConcurrentHashMap same time? (answer)
Yes, ConcurrentHashMap allows concurrent read without locking as reading operation doesn't require locking or thread-safety.

Can one thread read and other writes on ConcurrentHashMap at the same time? (answer)
Yes, it's possible for a small number of the writer. For example, if a write operation is modifying one segment of ConcurrentHashmap and read operation is happening on other segments then a reader will not block, but if reader thread is also trying to read from the same segment than it will block until the writer is done.

How does ConcurrentHashMap work internally? (answer)
The java.util.ConcurrentHashMap works similar to HashMap when it comes to storing key/value pairs and retrieving values. The only difference in its implementation comes from concurrency perspective and how it achievers thread-safety. It divides the map into several segments, by default 16, also known as synchronization level.

Because of this, concurrent get(), put(), contains() operation is possible because it never locks the whole map but only relevant segment is locked. Which means readers can access the map concurrency with writers and a limited number of writers can modify the map concurrently. The result is better throughput and Scalability. See Java Concurrency in Practice for details on the implementation of ConcurrentHashMap class.

Here is a diagram which explains how a segment looks like in a ConcurrentHashMap of Java, basically it's nothing but a mini hash table with a bucket and linked list of hash entries in case of collision:

Top 10 Java ConcurrentHashMap Interview Questions and Answers

Since the Iterator returned by ConcurrentHashMap is weakly consistent, the recent concurrency modification may or may not be visible to it. There is no guarantee offered on such operation. I suggest you reading Java Concurrency in Practice to learn more about how concurrency is handled by ConcurrentHashMap in Java.

How do you atomically update a value in ConcurrentHashMap? (answer)
If you want to atomically update an existing value in ConcurrentHashMap, you can use the replace() function of concurrentHashMap. It accepts both old value and new value and only updates the map if the existing value in the map matches with the old value provided, this means the map is not concurrently modified during its call. If the existing value is changed and not matches with the old value then replace fail with returning false. You can use call the replace() method in while loop until you succeed, as shown below:

ConcurrentMap<String, Long> populationByCities = new ConcurrentHashMap<>();
  Long currentValue = populationByCities.get("New York");
  Long newValue = currentValue == null ? 1 : currentValue + 1;
}while(!populationByCities.replace("New York", currentValue, newValue));

You can also see Java SE 8 for Really Impatient for some code examples of atomically updating an existing value in ConcurerntHashMap.

How do you remove a mapping while iterating over ConcurrentHashMap? (answer)
You can use an Iterator to remove a mapping from ConcurrentHashMap in Java as shown below:

Map<String, Integer> bookAndPrice = new ConcurrentHashMap<>();
bookAndPrice.put("Effective Java", 42);
bookAndPrice.put("Head First Java", 29);
bookAndPrice.put("Java Concurrency in Practice", 33);
bookAndPrice.put("Head First Design Patterns", 41);

System.out.println("before removing : " + bookAndPrice);
Iterator<String> iterator = bookAndPrice.keySet().iterator();


System.out.println("after removing : " + bookAndPrice);

before removing : {Java Concurrency in Practice=33,
 Head First Design Patterns=41, Effective Java=42, Head First Java=29}
after removing : {Head First Design Patterns=41}

Does Iterator of ConcurrentHashMap is fail-safe or fail-fast? (answer)
Iterator of ConcurrentHashMap is a fail-safe iterator which means it will not throw a ConcurrentModificationException, thus, eliminating the need to lock the map during iteration. The iterator returned by ConcurrentHashMap are also weakly consistent which means if the Map is modified during iteration, it may or may not reflect the recent modification. Generally, it creates a copy of collection before iterating.

What will happen if you add a new mapping in ConcurrentHashMap while one thread is iterating over it? (answer)
This is one of the tricky questions related to ConcurrentHashMap. Since iterator's of ConcurrentHashMap are weekly consistent and fail-safe they will not fail with ConcurrentModificationException but it's also possible that they won't see any modification once iteration started. Even though it's implementation dependent, JDK generally creates a separate copy of ConcurrentHashMap for iteration, instead of iterating over original copy.

Can you pass an object of ConcurrentHahsMap when a Map is expected? (answer)
Yes because ConcurrentHashMap implements java.util.concurrent.ConcurrentMap interface, which extends java.util.Map interface, hence ConcurrentHashMap IS-A Map. Also, you can store an object of ConcurrentHashMap into a Map variable as shown below:

Map<String, Integer> bookAndPrice = new ConcurrentHashMap<>();

Though, this means, you may not have access to methods declared in the java.util.concurrent.ConcurrentHashMap class e.g. forEachKey() or forEachValue() method added in JDK 8.

That's all about some of the frequently asked questions about ConcurrentHashMap on Java interviews. These questions will not only help you to do well on your job interview but also encourage you to learn more about ConcurrentHashMap. A good and solid knowledge of ConcurrentHashMap is expected from both junior and senior Java developer given its importance and usability in every Java application. At least you should be comfortable with day-to-day operations with ConcurrentHashMap and understand how the internal implementation works, especially when compared to other thread-safe map implementations e.g. Hashtable and Synchronized HashMap.

Further Reading
Java Programming Interview Exposed
Java Fundamentals: Collections
From Collections to Streams in Java 8 Using Lambda Expressions

Other Java Interview Questions list you may want to check
50 Java Programs from Coding Interviews (list)
10 Java Garbage Collection Interview Questions (list)
21 Java Final modifier Interview Questions (list)
21 Java Inheritance Interview Questions with answers (list)
10 Date, Time, and Calendar based Interview Questions with answers (list)
5 main() method interview questions (list)
19 Java Overloading and Overriding Interview Questions (list)
15 Java NIO and Networking Interview Questions with Answers (see here)
21 Java ArrayList Interview Questions with Answers (list)
15 SQL and UNIX questions from Java Interviews (list)
22 array concept interview questions from Java (list)
25 Java Collection Framework Interview Questions with Answers (list)
15 Java Enum based Interview Questions (list)

Thanks for reading this article so far. If you like these interview questions and find my explanations useful then please share with your friends and colleagues. If you have any question or doubt then please drop a comment.


praveen pusarla said...

Your blog is wonderful.. But we need to search all the concepts you shared for particular topic. ex.. If i want to learn on topic Multi threading
the concepts and examples i need to search throughout your blogs.

Javin Paul said...

Hello praveen, you can use lables for that e..g if you click on the lables in this article about collection interview questions, all post with that topic will come up and you can navigate them using paginated links.

Post a Comment