Saturday, April 9, 2016

Concurrent Hash map with example

Generally If you are modify map object during run time, you will get exception as concurrent modification exception. To avoid this java brings a good concept called concurrent hash map from java 1.5. It is placed inside java.util.concurrent package.

Let start with a simple example and we can move depth.

package com.test.javahit;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
public class Fruits {
 
    public static void main(String[] args) {
 
        //Declaring ConcurrentHashMap
        Map map = new ConcurrentHashMap();
        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        map.put("4", "4");
        map.put("5", "5");
        map.put("6", "6");

        System.out.println("ConcurrentHashMap before using iterator: "+map);
        Iterator it = map.keySet().iterator();
        
        while(it.hasNext()){
            String key = (String) it.next();
            if(key.equals("3")) map.put("newKey", "newValue");
        }
        System.out.println("ConcurrentHashMap after using iterator: "+map);
 
        //Declaring HashMap
        map = new HashMap();
        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        map.put("4", "4");
        map.put("5", "5");
        map.put("6", "6");
        System.out.println("HashMap before iterator: "+map);
        Iterator iterator1 = map.keySet().iterator();
 
        while(iterator1.hasNext()){
            String key = (String) iterator1.next();
            if(key.equals("3")) map.put("new", "newValue");
        }
        System.out.println("HashMap after using iterator: "+map);
    }
 
}

Now just run the program and check the output.
ConcurrentHashMap before using iterator: {1=1, 5=5, 6=6, 3=3, 4=4, 2=2}
ConcurrentHashMap after using iterator: {1=1, newKey=newValue, 5=5, 6=6, 3=3, 4=4, 2=2}
HashMap before iterator: {3=3, 2=2, 1=1, 6=6, 5=5, 4=4}
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
 at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at com.test.javahit.Fruits.main(Fruits.java:42)
From the above example, you could understand concurrent hashmap you can modify data while doing iteration and in hashMap can not.

We can see more, how its working. 

How to Initialize ?

It will be too good, if we will initialize with constructor parameters. For more understanding see below.

ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<String, Integer>();

ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<String, Integer>(16, 0.9f, 1);

Above two codes are just declaring the concurrent Hash Map. But Second declartion approach is good compared to first one. The reason behind is,

syntax for initializing constructor with concurrent Hash Map

ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)

1. initialCapacity - capacity level size
2. loadFactor - Capacity level crossed means, how to add more capacity size
3. concurrencyLevel - Simply we can say thread level

As we all have good idea about first two points , but 3rd one concurrency level is just different. 16 number of concurrent threads can play with concurrent hash map. Before you set concurrency level, better to analyze more with your application. Since it will play huge performance.

Internally concurrent hash map will be divided into 16 number of participation and will assign each thread to one partition. It will maintain thread safety.  so that it will not throw any concurrent exception.

Points to Remember

1. Always use this when your project need huge concurrency level.
2. No need to synchronize separately. 
3. It performance will be good compared to synchronized hash map and hast table.
4. It wont allow both null key and null value.
5. It will lock particular portion of map only while doing update operation.

No comments:

Post a Comment