Top 10 ConcurrentHashMap Questions from Java Interviews
The ConcurrentHashMap class part of concurrent collections package added on JDK 1.5 which contains utility classes likeBlockingQueue, 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 of the classic Java book of all time, the Java Concurrency in Practice book 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 Java programmer.
If you still find concepts difficult to understand you can also take help from Heinz Kabutz's awesome courseJava Concurrency in Practice Bundle, which is based on this book. Heinz is one of the Java champion and excellent instructor who has 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.
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 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.
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 atJava Fundamentals: Collections course on Pluarlsight.
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 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.
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 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.
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 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 the 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.
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 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 a linked list of hash entries in case of collision:
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 also suggest you joining courseJava Concurrency in Practice Bundle, 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 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<>(); do{ Long currentValue = populationByCities.get("New York"); Long newValue = currentValue == null ? 1 : currentValue + 1; }while(!populationByCities.replace("New York", currentValue, newValue));
You can also seeJava SE 8 for Really Impatient for some code examples of atomically updating an existing value in ConcurerntHashMap.
8. 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(); 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 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.
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 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.
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.
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 Learning
The Complete Java MasterClass
Java Fundamentals: Collections
Data Structures and Algorithms: Deep Dive Using Java
OtherJava 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 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.
Join the conversation