avatarVikram Gupta

Summary

The provided web content discusses the differences between HashMap and ConcurrentHashMap in Java, focusing on their suitability for concurrent use and the issues that may arise when modifying a HashMap during iteration.

Abstract

The article "Comparing HashMap and ConcurrentHashMap in Java" delves into the internal workings and interview-relevant aspects of these two key Java collection classes. It explains that HashMap is a widely-used class for storing key-value pairs but is not thread-safe, leading to ConcurrentModificationException when modified during iteration. In contrast, ConcurrentHashMap is designed for concurrent access and modification, preventing such exceptions and ensuring thread safety. The author recommends using ConcurrentHashMap in multi-threaded environments to avoid synchronization issues that arise with HashMap. The article also provides code examples to illustrate the problems with HashMap during concurrent modifications and demonstrates how ConcurrentHashMap addresses these issues effectively.

Opinions

  • The author suggests that developers should be aware of the limitations of HashMap when it comes to thread safety and the potential for ConcurrentModificationException during iteration.
  • It is emphasized that ConcurrentHashMap is the preferred choice for applications that require concurrent access to a map, as it avoids the pitfalls of HashMap in such scenarios.
  • The article implies that understanding the internal mechanisms of these classes is crucial for Java developers, especially when preparing for interviews.
  • The author advocates for the use of ConcurrentHashMap over HashMap when dealing with multi-threaded applications, highlighting its robustness in handling concurrent operations without the need for explicit synchronization.

Java Collection Interview Questions

Comparing HashMap and ConcurrentHashMap in Java

Know the differences between the most widely used collection classes.

HashMap with Singly Linked List

In the last article, I have explained the internal working mechanism of the hashMap and everything you may be asked in the interviews. Now, this is another interesting question that is generally asked in interviews → What are the differences between HashMap and CocurrentHashMap?

Through the medium of this article, we’ll see how these are different and their working mechanism.

Before we jump into this topic I would recommend you go through the below article which will clear your concepts related to HashMap and its internal working mechanism. This article is a continuation of the last article.

What is HashMap?

  • Basically, HashMap is one of the most popular Collection classes in the Java collection framework. HashMapinternally uses HashTable implementation. This HashMap class extends AbstractMap class that implements the Mapinterface.
  • HashMap stores the entries in the form of a key-value pair and allows at max one null key and multiple null values.
  • Java HashMap is not thread-safe and hence it should not be used in multithreaded applications. For the multi-threaded applications, we should use ConcurrentHashMap class.

What is ConcurrentHashMap?

  • Java ConcurrentHashMap class is part of the Collection classes in the Java collection framework.

Basically, it is a HashTable implementation, that supports concurrent retrieval and updates in the map.

  • Hence it can be used in multi-threaded applications to avoid ConcurrentModificationException.
  • While iterating over a hashmap using an iterator, if we try to modify the structure of the map(i.e. the number of entries (either remove or put a new entry in the map)), then we get ConcurrentModificationException. To get rid of this exception and to change the structure of the map we should use ConcurrentHashMap.
  • The ConcurrentHashMap operations are thread-safe.

ConcurrentHashMap doesn’t allow null for keys and values. If we try to add null key or value it throws NullPointerException.

The ConcurrentHashMap class is similar to HashMap, except it’s thread-safe and allows modification while iterating over it.

What Is the Issue With HashMap While Iterating Over It?

Let’s see a program to understand this.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ExceptionExample {

    public static void main(String[] args) {
        Map<String, Long> phoneBook = new HashMap<String, Long>();
        phoneBook.put("Vikram",8149101254L);
        phoneBook.put("Mike",9020341211L);
        phoneBook.put("Jim",7788111284L);

        Iterator<String> keyIterator = phoneBook.keySet().iterator();

        while (keyIterator.hasNext()){
            String key = keyIterator.next();
            if ("Vikram".equals(key)){
                phoneBook.put("John",9220341211L);
            }
        }
    }
}

Output:

Exception in thread “main” java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextNode(HashMap.java:1445)
 at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
 at ExceptionExample.main(ExceptionExample.java:16)
  1. When a new entry is inserted into the HashMap, the Iterator for the keys fails. The Iterator on Collection objects is fail-fast i.e. any modification in the structure or the number of entries in the collection object(here map object) will trigger this exception.
  2. Hence the exception ConcurrentModificationException is thrown. Basically, HashMap contains a variable to count the number of modifications and the iterator uses it when you call its next() function to get the next entry.

The above scenario can be overcome using ConcurrentHashMap and hence it’s advised not to use hashmap where the structure of the map is modified.

What if the Existing Key-Value Pair Is Updated and No New Entry Is Added to the Map? Will It Throw an Exception?

In the above program, inside the if condition, if we update an existing key-value pair using the put method as shown below:

phoneBook.put("Vikram", "8149001100");

In this case, there won’t be any exception because the map is modified but the map’s structure remains the same(i.e. the number of entries in the map).

Now Let’s Try With ConcurrentHashMap:

Let’s use the ConcurrentHashMap instead of HashMap and see if this resolves our exception issue or not. Below piece of code below uses ConcurrentHashMap in place of HashMap.

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ExceptionExample {

    public static void main(String[] args) {
        Map<String, Long> phoneBook = new ConcurrentHashMap<String, Long>();
        phoneBook.put("Vikram", 8149101254L);
        phoneBook.put("Mike", 9020341211L);
        phoneBook.put("Jim", 7788111284L);

        Iterator<String> keyIterator = phoneBook.keySet().iterator();

        System.out.println("Map Content before modification : " + phoneBook);
        while (keyIterator.hasNext()) {
            String key = keyIterator.next();
            if ("Vikram".equals(key)) {
                phoneBook.put("John", 9220341211L);
            }
        }
        System.out.println("Map Content after modification : " + phoneBook);
    }
}

Output:

Map Content before modification : {Mike=9020341211, Vikram=8149101254, Jim=7788111284}
Map Content after modification : {Mike=9020341211, John=9220341211, Vikram=8149101254, Jim=7788111284}

On line number 18, we have added a new entry in the map same as the previous example while iterating over the map. But this time we don’t see an exception in the output.

The reason behind this is, that the iterator and the map both are backing each other so that they keep track of changes in one another.

That’s all for this article. Hope you enjoyed it.

You Can Follow Vikram Gupta For Similar Content.

1. Comparing ArrayList and LinkedList in Java

2. Internal Working of HashMap in Java

3. Comparing HashMap and ConcurrentHashMap in Java

4. Complete the Guide on LinkedHashMap in Java

5. Internal Working Of TreeMap in Java Collection Framework

6. Internal Working of HashSet in Java

Java Concurrenthashmap
Hashmap Concurrenthashmap
Collections Questions
Java Programming
Concurrent Hash Map
Recommended from ReadMedium