Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Synchronized java.util.HashMap vs. java.util.concurrent.ConcurrentHashMap

DZone's Guide to

Synchronized java.util.HashMap vs. java.util.concurrent.ConcurrentHashMap

Find out what using java.util.concurrent.ConcurrentHashMap means to the performance of the application.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Using java.util.HashMap from many threads without any synchronization leads to race conditions. So we need some kind of synchronization. The easiest way is to synchronize the complete class. Another way is to use a java.util.concurrent.ConcurrentHashMap. But what does this mean to the performance of the application?
As an example we use a HashMap to count the occurrence of a String:

import java.math.BigInteger;
import java.security.SecureRandom;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;

@State(Scope.Benchmark)
public class MyBenchmark {
    private HashMapBasedCollectionmap = new HashMapBasedCollection();

    private String nextSessionId(SecureRandom random) {
        return new BigInteger(130, random).toString(32);
    }

    public String[] buildNames(int size) {
        SecureRandom random = new SecureRandom();

        String[] result = new String[size];

        for (int i = 0; i < size; i++) {
            result[i] = nextSessionId(random);
        }

        return result;
    }

    @Benchmark
    public void testMethod() {
        String[] array = buildNames(40);
        for (int j = 0; j < 200; j++) {
            for (int i = 0; i < 40; i++) {
                map.addOne(array[i]);
            }
        }

    }

}
import java.util.HashMap;
import java.util.function.BiFunction;

public class HashMapBasedCollection {

    private HashMap<String,Integer> map = new HashMap<String,Integer>();

    public static final BiFunction<String, Integer, Integer> fun
    = new BiFunction<String, Integer, Integer>()
    {

        @Override
        public Integer apply(String t, Integer u) {
            if( u == null )
            {
                return new Integer(0);
            }        
            return u + 1;
        }

    };

    /**
     * 
     * Warning: not thread safe
     * 
     */

    public void addOne(String key)
    {
        map.compute(key,  fun);
    }

}

As expected if we run the method “testMethod()” with two threads we see a race condition. Output from vmlens, a tool to detect race conditions:
race_hash_map

So we need to use java.util.HashMap with synchronization:

public class SynchronizedHashMapBasedCollection {

    private HashMap<String,Integer> map = new HashMap<String,Integer>();

    public synchronized void addOne(String key)
    {
        map.compute(key,  HashMapBasedCollection.fun);
    }

}

Or a java.util.concurrent.ConcurrentHashMap:

public class ConcurrentHashMapBasedCollection {

    private final ConcurrentHashMap<String,Integer> map = new ConcurrentHashMap<String,Integer>();

    public void addOne(String key)
    {
        map.compute(key,  HashMapBasedCollection.fun );
    }

}

Below you see the throughput for the two implementations for different counts of thread.
concurrentVsSynchronized
That the performance of the ConcurrentHashMap for many threads is better is probably no surprise. What surprised me is that the performance for one thread is the same. This means ConcurrentHashMap is a good alternative to synchronized HashMap even for few threads.
The benchmark was created using jmh. The race condition was detected by vmlens.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,concurrency

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}