Friday, October 13, 2017

ConcurrentHashMap in Java8 with Example

In this post we will learn about concurrentHashMap in Java 8. We will cover the concepts what is concurrentHashMap,advantage of concurrentHashMap with simple examples and also we will check how to create concurrentHashSet from the concurrentHashMap.

From Java5 ConcurrentHashMap is introduced as another alternative for HashTable.There is no ConcurrentHashSet in JDK8 but you can still create one for yourself by using the ConcurrentHashMap class of java.util.concurrent package. There is a new method added into ConcurrentHashMap in JDK 8, newKeySet(), which allows you to create a concurrent hash set backed by a concurrent hash map.If you remember whenever you get keys from the map they are returned in a Set e.g. for the old keySet() method because map only has unique keys. Since map doesn't allow duplicate keys, it can be used as a set, as long as you only care for keys or just one element. That's why Java designers are added newKeySet() method to convert a map to set. This is also a static method, which means you don't need a ConcurrentHashMap object to create a concurrent hash set.

How Performance improved:

ConcurrentHashMap is also a hash based map like HashMap, how it differs is the locking strategy used by ConcurrentHashMap. Unlike HashTable (or synchronized HashMap) it doesn't synchronize every method on a common lock. ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map. Just for information ConcurrentHashMap uses ReentrantLock for locking.

How to create simple example of ConcurrentHashMap:

public class Demo {
public static void main(String[] args) {
// Creating ConcurrentHashMap
Map<String, String> cityTemperatureMap = new ConcurrentHashMap<String, String>();
// Storing elements
cityTemperatureMap.put("Mumbai", "38");
cityTemperatureMap.put("chennai", "40");
//cityTemperatureMap.put(null, "23");
cityTemperatureMap.put("Bangalore", "26");
cityTemperatureMap.put("Hyderabad", "34" );
for (Map.Entry e : cityTemperatureMap.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
}
}

Null is not allowed
Though HashMap allows one null as key but ConcurrentHashMap doesn't allow null as key. In the previous example you can uncomment the line which has null key. While trying to execute the program it will throw null pointer exception.

Exception in thread "main" java.lang.NullPointerException
 at java.util.concurrent.ConcurrentHashMap.putVal(Unknown Source)
 at java.util.concurrent.ConcurrentHashMap.put(Unknown Source)
 at byluckysir.prog.Demo.main(Demo.java:16)

Java Program to create ConcurrentHashSet:
Here is our Java program to demonstrate how you can generate a ConcurrentHashSet in JDK 8 by using the newKeSet() method added into java.util.concurrent.ConcurrentHashMap class. Even though I have used an object of the concurrent hash map here, it's not required because unlike keySet(), the newKeySet() is a static method.

Let's the code to actually generate a concurrent hash set in Java 8:

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/*
 * Java Program to create ConcurrentHashSet from ConcurrentHashMap
 * This code requires JDK 8 because we use newKeySet() method
 * which is only available in ConcurrentHashMap class from JDK 8. 
 */
public class Test {
public static void main(String[] args) throws Exception {
// step 1 - create a concurrent hashmap (optional)
 ConcurrentHashMap<String, Integer> wordLengh = new ConcurrentHashMap<>();
// step 2 - create a set from map by using newKeySet() method
// provide size to prevent resizing and better performance
Set<String> words = ConcurrentHashMap.newKeySet(wordLengh.size());
// step 3 - you can add elements into set
 words.add("JavaBook");
words.add("JavaScript");
// step 4 - you can remove elements from set
words.remove("JavaScript");
// step 5 - you can also pass this set to any method expecting set
System.out.println(words);
}
}
Output:
Java

You can see that you can easily add and remove elements from the Set returned by newKeySet() method. As I said, the Set is backed by ConcurrentHashMap, which means multiple readers can retrieve values at the same time and also multiple writers can insert values into the set without blocking, until the read and write operation is happening in the same segment.

concurrent hash map never locks the whole map, instead, it divides the map into several segments, by default 16, also knowns as concurrency level and only locks the segment where modification is happening. This means multiple writes is possible if they are happening at different segments.

The concurrent hash set is not only thread-safe set which is available in JDK, you have some more choices e.g. you can use CopyOnWriteArraySet, which is similar to CopyOnWriteArrayList i.e. it copies the whole collection into new one whenever a write happens but because of this behavior they are only useful for a set with small number of elements with infrequent write.

When ConcurrentHashMap is a better choice:

ConcurrentHashMap is a better choice when there are more reads than writes. As mentioned above retrieval operations are non-blocking so many concurrent threads can read without any performance problem. If there are more writes and that too many threads operating on the same segment then the threads will block which will deteriorate the performance.

Points to Remember:

  • ConcurrentHashMap is also a hash based map like HashMap, but ConcurrentHashMap is thread safe.
  • In ConcurrentHashMap thread safety is ensured by having separate locks for separate buckets, resulting in better performance.
  • By default the bucket size is 16 and the concurrency level is also 16.
  • No null keys are allowed in ConcurrentHashMap.
  • Iterator provided by the ConcurrentHashMap is fail-safe, which means it will not throw ConcurrentModificationException.
  • Retrieval operations (like get) don't block so may overlap with update operations (including put and remove).


This is all about concept of ConcurrentHashMap in java 8. If you have doubt or any suggestions to make drop a comment..






No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...