Friday, April 16, 2021

Top 10 Java ConcurrentHashMap Interview Questions with Answers [UPDATED]

The ConcurrentHashMap class part of concurrent collections package added on JDK 1.5 which contains utility classes like 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 the 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 a little risk, as advised in one of the classic Java books of all time, the Java Concurrency in Practice by Brian Goetz.

If you have not read this book then I highly recommend it to every single Java programmer. Many of you may find it difficult when you read it the first time but persist with it and you will reap the dividend in your career as a Java programmer.

If you still find concepts difficult to understand you can also take help from Heinz Kabutz's awesome course Java Concurrency in Practice Bundle, which is based on this book. Heinz is one of the Java champions and excellent instructors who have gifted teaching skills. He explains difficult concepts in such an easy language and examples which you can correlate.

Anyway, let's start with this list of Java interview questions based upon ConcurrentHashMap class and concepts around it.




10 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.


1. 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.


2. Does ConcurrentHashMap thread-safe in Java? (answer)
Yes, ConcurrentHashMap is thread-safe in Java, which means two threads 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.


3. 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, unlike HashMap, it never locks the whole map. This technique is also known as lock stripping.

If you want to learn more about it, you can also take a look at the Java Collections from basics to Advanced courses on Udemy.

How concurrent hashmap works in Java




4. 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.


5. Can one thread read and the 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 the reader thread is also trying to read from the same segment then it will block until the writer is done.


6. 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 the concurrency perspective and how it achieves 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 the relevant segment is locked. This 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.

You can further see The Complete Java MaseterClasss course on Udemy for details on the implementation of ConcurrentHashMap class. This course is recently updated for Java 11, the latest Java version as well.

Here is a diagram that explains how a segment looks like in a ConcurrentHashMap of Java, basically it's nothing but a mini hash table with a bucket and a 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 an operation.

I  also suggest you join the course Java Multithreading, Concurrency & Performance Optimization to learn more about how concurrency is handled by ConcurrentHashMap in Java.



7. 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 concurrent hashmap.

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 match with the old value then replace fail with returning false. You can use call the replace() method in the while loop until you succeed, as shown below:

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

You can also see the Java Collections: Fundamentals course by Richard Warburton, another Java Champion on Pluralsight to learn about basic Collection classes in Java. 

concurrent hashmap interview questions with answers

Btw, you would need a Pluralsight membership to access this course, which costs around $29 monthly or $299 annually. I have one and I also suggest all developers have that plan because Pluralsight is like NetFlix for Software developers. It has more than 5000+ good quality courses on all the latest topics. Since we programmers have to learn new things every day, an investment of $299 USD is not bad.

Btw, it also offers a 10-day free trial without any obligation which allows you to watch 200 hours of content. You can watch this course for free by signing for that trial.


8. How do you remove a mapping while iterating over ConcurrentHashMap? (answer)
You can use an Iterator to remove the 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();

while(iterator.hasNext()){
  if(iterator.next().contains("Java")){
  iterator.remove();
}
}


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

Output
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}



9. Does the 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 is 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 the collection before iterating.



10. 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 iterators of ConcurrentHashMap are weakly 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 an original copy.


11. 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 Java 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.

Good and solid knowledge of ConcurrentHashMap is expected from both junior and senior Java developers 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 like Hashtable and Synchronized HashMap.


Further Learning
The Complete Java MasterClass
Java Fundamentals: Collections
Java Multithreading, Concurrency & Performance Optimization


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)
  • 20 Spring MVC Interview Questions for 2 to 5 years experienced Java Programmers (list)
  • 15 Spring Boot Interview Questions for Java developers (list)
  • 20 REST and Spring-based Questions for Java developers (list)

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

P. S. - If you are new to Java Programming and looking for a free online course to learn Java from scratch then I highly recommend this Java Tutorial for Complete Beginners(FREE) course on Udemy. It's completely free and more than 1.2 million people have already joined this to learn Java on their own. 

6 comments :

Hadoop-Knowledge 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.

Unknown said...

I think you note about read + write is incorrect, reads are not at all blocks whether or not some other thread is writing in same segment.

Anonymous said...

Can someone please confirm this?

Unknown said...

Since jdk9 ConcurrentHashMap is not divided on segments at all (here stated that map is divided on 16 segments by default).
In fact, each bucket (or bin) has its own lock (first element in bucket serves as lock by itself), but it is only used when there are any hash collisions.
If no collisions than lock-free approach is used.

Alex said...

> are weekly consistent
are weakly consistent

Post a Comment