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

November 15, 2015

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.

Make your application thread safe

LEARN MORE