Over a million developers have joined DZone.

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

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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;

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;

    public void testMethod() {
        String[] array = buildNames(40);
        for (int j = 0; j < 200; j++) {
            for (int i = 0; i < 40; 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>()

        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:

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.
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.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}