Java Hashtable, HashMap, ConcurrentHashMap: Performance Impact

There are a good number of articles that articulate functional differences between HashMap, Hashtable, and ConcurrentHashMap. This post compares the performance behavior of these data structures through practical examples. If you don’t have the patience to read the entire post, here is the bottom line: when you are confronted with the decision of whether to use HashMap, Hashtable, or ConcurrentHashMap, consider using ConcurrentHashMap since it’s thread-safe implementation without compromise in performance.

Performance Study

 To study the performance characteristics, I have put together this sample program:

10 Examples of ConcurrentHashMap in Java

As a Java programmer, you might have heard about the ConcurrentHashMapclass of java.util.concurrent package. If you don't let me tell you that ConcurrentHashMap is an important class in Java and you will often find yourself dealing with this class in a multithreaded and concurrent Java application. If you are wondering where to start and how to master this essential Java class then you have come to the right place.

In this article, I have shared some of the frequently used examples of ConcurrentHashMap in Java-like how to create a ConcurrentHashMap, how to update a key or value, how to delete a key-value pair, how to check if a key exists in ConcurrentHashMap or not, how to add new key-value pairs, and how to retrieve values from ConcurrentHashMap in Java.

Once you have gone through these examples, you will have a better understanding of ConcurrentHashMap and you will be more confident in using them in your Java program without causing subtle bugs that are hard to find and fix.

ConcurrentHashMap: Call Only One Method Per Key

Each method of ConcurrentHashMap is thread-safe. But calling multiple methods from ConcurrentHashMap for the same key leads to race conditions. And calling the same method from ConcurrentHashMap recursively for different keys leads to deadlocks.

Let us look at an example to see why this happens: