The ConcurrentHashMap cast component subdivision of concurrent collections parcel 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 together with synchronized HashMap. It implements Map together with ConcurrentMap (a sub-interface of Map) interface which allows you lot to shop key-value pairs. The cast is similar to HashMap or Hashtable merely it's to a greater extent than scalable and the correct fit for concurrent Java application. Unlike Hashtable which achieves its thread-safety past times compromising the scalability, ConcurrentHashMap uses advanced techniques e.g. dividing the map into segments to stay thread-safe together with scalable at the same time.
Because of its performance together with scalability equally good equally thread-safety, it is the most pop pick of Map inwards concurrent Java applications.
In general, replacing synchronized collections amongst a concurrent collection tin terminate dramatically improve the scalability of your Java application amongst a picayune risk, equally advised inwards of the classic Java mass of all time, the Java Concurrency inwards Practice book past times Brian Goetz.
If you lot receive got non read this mass together with so I highly recommend it to every unmarried Java programmer. Many of you lot may abide by it hard when you lot read it the commencement fourth dimension merely persist amongst it together with you lot volition reap the dividend inwards your career equally Java programmer.
If you lot even so abide by concepts hard to empathise you lot tin terminate too convey aid from Heinz Kabutz's awesome course Java Concurrency inwards Practice Bundle, which is based on this book. Heinz is i of the Java champion together with first-class teacher who has gifted teaching skills. He explains hard concepts inwards such an slowly linguistic communication together with examples which you lot tin terminate correlate.
Anyway, let's start amongst this listing of Java interview questions based upon ConcurrentHashMap cast together with concepts some it.
These questions volition non alone aid you lot to reach good on interviews merely too encourage you lot to larn to a greater extent than almost the concurrent hash map, which volition eventually aid you lot inwards your twenty-four lx minutes menses to twenty-four lx minutes menses programming job.
1. What is ConcurrentHashMap inwards Java? (answer)
The java.util.concurrent.ConcurrentHashMap is a concurrent collection cast added on JDK 1.5 equally a replacement of synchronized hash-based map implementations e.g. Hashtable together with synchronized HashMap. They offering amend performance together with scalability over their synchronized counterpart amongst picayune risk.
2. Does ConcurrentHashMap thread-safe inwards Java? (answer)
Yes, ConcurrentHashMap is thread-safe inwards Java, which agency 2 thread tin terminate modify the map without damaging its internal information construction e.g. array together with linked list. If you lot compare this to HashMap, which is non thread-safe, exposing HashMap to multiple threads may harm internal information structure together with may homecoming the map completely useless, where many links may acquire missing or pointing to incorrect elements.
3. How does ConcurrentHashMap scope thread-safety? (answer)
The java.util.ConcurrentHashMap achieves thread-safety past times dividing the map into segments together with locking alone the segment which requires instead of locking the whole map. So, yes, it achieves thread-safety using locking merely it performs amend because different HashMap, it never locks the whole map. This technique is too known equally lock stripping.
If you lot desire to larn to a greater extent than almost it, you lot tin terminate too convey a facial expression at answer)
Yes, ConcurrentHashMap allows concurrent read without locking equally reading performance doesn't require locking or thread-safety.
5. Can i thread read together with other writes on ConcurrentHashMap at the same time? (answer)
Yes, it's possible for a pocket-size pose out of the writer. For example, if a write performance is modifying i segment of ConcurrentHashmap together with read performance is happening on other segments together with so a reader volition non block, merely if reader thread is too trying to read from the same segment than it volition block until the author is done.
6. How does ConcurrentHashMap locomote internally? (answer)
The java.util.ConcurrentHashMap plant similar to HashMap when it comes to storing key/value pairs together with retrieving values. The alone departure inwards its implementation comes from concurrency perspective together with how it achievers thread-safety. It divides the map into several segments, past times default 16, too known equally synchronization level.
Because of this, concurrent get(), put(), contains() performance is possible because it never locks the whole map merely alone the relevant segment is locked. Which agency readers tin terminate access the map concurrency amongst writers together with a express pose out of writers tin terminate modify the map concurrently. The result is amend throughput together with Scalability.
You tin terminate farther come across The Complete Java MaseterClasss course of teaching on Udemy for details on the implementation of ConcurrentHashMap class. This course of teaching is of late updated for Java 11, the latest Java version equally well.
Here is a diagram which explains how a segment looks similar inwards a ConcurrentHashMap of Java, basically it's nil merely a mini hash tabular array amongst a bucket together with a linked listing of hash entries inwards instance of collision:
Since the Iterator returned past times ConcurrentHashMap is weakly consistent, the recent concurrency modification may or may non live on visible to it. There is no guarantee offered on such operation.
I too advise you lot joining course Java Concurrency inwards Practice Bundle, to larn to a greater extent than almost how concurrency is handled past times ConcurrentHashMap inwards Java.
7. How reach you lot atomically update a value inwards ConcurrentHashMap? (answer)
If you lot desire to atomically update an existing value inwards ConcurrentHashMap, you lot tin terminate role the replace() component subdivision of concurrentHashMap.
It accepts both one-time value together with novel value together with alone updates the map if the existing value inwards the map matches amongst the one-time value provided, this agency the map is non concurrently modified during its call.
If the existing value is changed together with non matches amongst the one-time value together with so supersede neglect amongst returning false. You tin terminate role telephone phone the replace() method inwards spell loop until you lot succeed, equally shown below:
You tin terminate too see Java SE 8 for Really Impatient for some code examples of atomically updating an existing value inwards ConcurerntHashMap.
8. How reach you lot take away a mapping spell iterating over ConcurrentHashMap? (answer)
You tin terminate role an Iterator to take away a mapping from ConcurrentHashMap inwards Java equally shown below:
9. Does Iterator of ConcurrentHashMap is fail-safe or fail-fast? (answer)
Iterator of ConcurrentHashMap is a fail-safe iterator which agency it volition non throw a ConcurrentModificationException, thus, eliminating the demand to lock the map during iteration.
The Iterator returned past times ConcurrentHashMap are too weakly consistent which agency if the Map is modified during iteration, it may or may non reverberate the recent modification. Generally, it creates a re-create of collection earlier iterating.
10. What volition come about if you lot add together a novel mapping inwards ConcurrentHashMap spell i thread is iterating over it? (answer)
This is i of the tricky questions related to ConcurrentHashMap. Since iterator's of ConcurrentHashMap are weekly consistent together with fail-safe they volition non neglect amongst ConcurrentModificationException merely it's too possible that they won't come across whatever modification in i trial iteration started. Even though it's implementation dependent, JDK mostly creates a separate re-create of ConcurrentHashMap for iteration, instead of iterating over master copy.
11. Can you lot top 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, so ConcurrentHashMap IS-A Map. Also, you lot tin terminate shop an object of ConcurrentHashMap into a Map variable equally shown below:
Though, this means, you lot may non receive got access to methods declared inwards the java.util.concurrent.ConcurrentHashMap cast e.g. forEachKey() or forEachValue() method added inwards Java 8.
That's all almost some of the frequently asked questions almost ConcurrentHashMap on Java interviews. These questions volition non alone aid you lot to reach good on your project interview merely too encourage you lot to larn to a greater extent than almost ConcurrentHashMap.
Influenza A virus subtype H5N1 expert together with enterprise cognition of ConcurrentHashMap is expected from both junior together with senior Java developer given its importance together with usability inwards every Java application.
At to the lowest degree you lot should live on comfortable amongst day-to-day operations amongst ConcurrentHashMap together with empathise how the internal implementation works, peculiarly when compared to other thread-safe map implementations e.g. Hashtable together with Synchronized HashMap.
Further Learning
The Complete Java MasterClass
list)10 Java Garbage Collection Interview Questions (list) 21 Java Final modifier Interview Questions (list) 21 Java Inheritance Interview Questions amongst answers (list) 10 Date, Time, together with Calendar based Interview Questions amongst answers (list) 5 main() method interview questions (list) 19 Java Overloading together with Overriding Interview Questions (list) 15 Java NIO together with Networking Interview Questions amongst Answers (see here) 21 Java ArrayList Interview Questions amongst Answers (list) 15 SQL together with UNIX questions from Java Interviews (list) 22 array concept interview questions from Java (list) 25 Java Collection Framework Interview Questions amongst Answers (list) 15 Java Enum based Interview Questions (list) 20 Spring MVC Interview Questions for 2 to five years experienced Java Programmers (list) 15 Spring Boot Interview Questions for Java developers (list) 20 REST together with Spring based Questions for Java developers (list)
Thanks for reading this article so far. If you lot similar these interview questions together with abide by my explanations useful together with so delight portion amongst your friends together with colleagues. If you lot receive got whatever interrogation or incertitude together with so delight drib a comment.
Because of its performance together with scalability equally good equally thread-safety, it is the most pop pick of Map inwards concurrent Java applications.
In general, replacing synchronized collections amongst a concurrent collection tin terminate dramatically improve the scalability of your Java application amongst a picayune risk, equally advised inwards of the classic Java mass of all time, the Java Concurrency inwards Practice book past times Brian Goetz.
If you lot receive got non read this mass together with so I highly recommend it to every unmarried Java programmer. Many of you lot may abide by it hard when you lot read it the commencement fourth dimension merely persist amongst it together with you lot volition reap the dividend inwards your career equally Java programmer.
If you lot even so abide by concepts hard to empathise you lot tin terminate too convey aid from Heinz Kabutz's awesome course Java Concurrency inwards Practice Bundle, which is based on this book. Heinz is i of the Java champion together with first-class teacher who has gifted teaching skills. He explains hard concepts inwards such an slowly linguistic communication together with examples which you lot tin terminate correlate.
Anyway, let's start amongst this listing of Java interview questions based upon ConcurrentHashMap cast together with concepts some it.
Java ConcurrentHashMap Interview Questions amongst Answers
Here are some of the best together with oftentimes asked Java ConcurrentHashMap interview questions. These questions are collected from the existent interview, hence, don't live on surprised if you lot receive got already seen them during interviews.These questions volition non alone aid you lot to reach good on interviews merely too encourage you lot to larn to a greater extent than almost the concurrent hash map, which volition eventually aid you lot inwards your twenty-four lx minutes menses to twenty-four lx minutes menses programming job.
1. What is ConcurrentHashMap inwards Java? (answer)
The java.util.concurrent.ConcurrentHashMap is a concurrent collection cast added on JDK 1.5 equally a replacement of synchronized hash-based map implementations e.g. Hashtable together with synchronized HashMap. They offering amend performance together with scalability over their synchronized counterpart amongst picayune risk.
2. Does ConcurrentHashMap thread-safe inwards Java? (answer)
Yes, ConcurrentHashMap is thread-safe inwards Java, which agency 2 thread tin terminate modify the map without damaging its internal information construction e.g. array together with linked list. If you lot compare this to HashMap, which is non thread-safe, exposing HashMap to multiple threads may harm internal information structure together with may homecoming the map completely useless, where many links may acquire missing or pointing to incorrect elements.
3. How does ConcurrentHashMap scope thread-safety? (answer)
The java.util.ConcurrentHashMap achieves thread-safety past times dividing the map into segments together with locking alone the segment which requires instead of locking the whole map. So, yes, it achieves thread-safety using locking merely it performs amend because different HashMap, it never locks the whole map. This technique is too known equally lock stripping.
If you lot desire to larn to a greater extent than almost it, you lot tin terminate too convey a facial expression at answer)
Yes, ConcurrentHashMap allows concurrent read without locking equally reading performance doesn't require locking or thread-safety.
5. Can i thread read together with other writes on ConcurrentHashMap at the same time? (answer)
Yes, it's possible for a pocket-size pose out of the writer. For example, if a write performance is modifying i segment of ConcurrentHashmap together with read performance is happening on other segments together with so a reader volition non block, merely if reader thread is too trying to read from the same segment than it volition block until the author is done.
6. How does ConcurrentHashMap locomote internally? (answer)
The java.util.ConcurrentHashMap plant similar to HashMap when it comes to storing key/value pairs together with retrieving values. The alone departure inwards its implementation comes from concurrency perspective together with how it achievers thread-safety. It divides the map into several segments, past times default 16, too known equally synchronization level.
Because of this, concurrent get(), put(), contains() performance is possible because it never locks the whole map merely alone the relevant segment is locked. Which agency readers tin terminate access the map concurrency amongst writers together with a express pose out of writers tin terminate modify the map concurrently. The result is amend throughput together with Scalability.
You tin terminate farther come across The Complete Java MaseterClasss course of teaching on Udemy for details on the implementation of ConcurrentHashMap class. This course of teaching is of late updated for Java 11, the latest Java version equally well.
Here is a diagram which explains how a segment looks similar inwards a ConcurrentHashMap of Java, basically it's nil merely a mini hash tabular array amongst a bucket together with a linked listing of hash entries inwards instance of collision:
Since the Iterator returned past times ConcurrentHashMap is weakly consistent, the recent concurrency modification may or may non live on visible to it. There is no guarantee offered on such operation.
I too advise you lot joining course Java Concurrency inwards Practice Bundle, to larn to a greater extent than almost how concurrency is handled past times ConcurrentHashMap inwards Java.
7. How reach you lot atomically update a value inwards ConcurrentHashMap? (answer)
If you lot desire to atomically update an existing value inwards ConcurrentHashMap, you lot tin terminate role the replace() component subdivision of concurrentHashMap.
It accepts both one-time value together with novel value together with alone updates the map if the existing value inwards the map matches amongst the one-time value provided, this agency the map is non concurrently modified during its call.
If the existing value is changed together with non matches amongst the one-time value together with so supersede neglect amongst returning false. You tin terminate role telephone phone the replace() method inwards spell loop until you lot succeed, equally 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 tin terminate too see Java SE 8 for Really Impatient for some code examples of atomically updating an existing value inwards ConcurerntHashMap.
8. How reach you lot take away a mapping spell iterating over ConcurrentHashMap? (answer)
You tin terminate role an Iterator to take away a mapping from ConcurrentHashMap inwards Java equally shown below:
Map<String, Integer> bookAndPrice = novel ConcurrentHashMap<>(); bookAndPrice.put("Effective Java", 42); bookAndPrice.put("Head First Java", 29); bookAndPrice.put("Java Concurrency inwards 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 earlier removing : {Java Concurrency inwards 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 agency it volition non throw a ConcurrentModificationException, thus, eliminating the demand to lock the map during iteration.
The Iterator returned past times ConcurrentHashMap are too weakly consistent which agency if the Map is modified during iteration, it may or may non reverberate the recent modification. Generally, it creates a re-create of collection earlier iterating.
10. What volition come about if you lot add together a novel mapping inwards ConcurrentHashMap spell i thread is iterating over it? (answer)
This is i of the tricky questions related to ConcurrentHashMap. Since iterator's of ConcurrentHashMap are weekly consistent together with fail-safe they volition non neglect amongst ConcurrentModificationException merely it's too possible that they won't come across whatever modification in i trial iteration started. Even though it's implementation dependent, JDK mostly creates a separate re-create of ConcurrentHashMap for iteration, instead of iterating over master copy.
11. Can you lot top 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, so ConcurrentHashMap IS-A Map. Also, you lot tin terminate shop an object of ConcurrentHashMap into a Map variable equally shown below:
Map<String, Integer> bookAndPrice = new ConcurrentHashMap<>();
Though, this means, you lot may non receive got access to methods declared inwards the java.util.concurrent.ConcurrentHashMap cast e.g. forEachKey() or forEachValue() method added inwards Java 8.
That's all almost some of the frequently asked questions almost ConcurrentHashMap on Java interviews. These questions volition non alone aid you lot to reach good on your project interview merely too encourage you lot to larn to a greater extent than almost ConcurrentHashMap.
Influenza A virus subtype H5N1 expert together with enterprise cognition of ConcurrentHashMap is expected from both junior together with senior Java developer given its importance together with usability inwards every Java application.
At to the lowest degree you lot should live on comfortable amongst day-to-day operations amongst ConcurrentHashMap together with empathise how the internal implementation works, peculiarly when compared to other thread-safe map implementations e.g. Hashtable together with Synchronized HashMap.
Further Learning
The Complete Java MasterClass
list)