Over a million developers have joined DZone.

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

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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.

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
java ,concurrency

Published at DZone with permission of Thomas Krieger, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}