How to Synchronize HashMap in Java

This post shows how to synchronize HashMap in Java and the HashMap’s thread safe alternative which can be used.

HashMap is not thread safe

If HashMap is accessed by multiple threads concurrently, and at least one of the threads modifies the map structurally, you must synchronize HashMap externally. Note that structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.

Options for thread-safe Map

If you want to synchronize HashMap in Java or looking for a thread-safe alternative of HashMap then there are following options.

  1. Use Collections.synchronizedMap() to synchronize Map– This method returns a synchronized (thread-safe) map backed by the specified map. In case you are synchronizing a TreeMap which is a sorted Map you can use synchronizedSortedMap() method
  2. Using ConcurrentHashMap– Another option is to use ConcurrentHashMap from the java.util.concurrent package. All of its operations are thread-safe and it provides better concurrency. ConcurrentHashMap provides better performance by using separate locks for separate buckets rather than synchronizing the whole Map on a single lock.

Using Collections.synchronizedMap()

You can synchronize your HashMap by using Collections.synchronizedMap() method. First we’ll see an example what happens if HashMap is used in a multi-threaded environment without synchronizing it.

Java program

In the Java code four threads are created, each of these thread adds 5 elements to the Map. After all the threads are done Map size should be 20.

Output

In different run I got different HashMap sizes, 17, 18, 19 and even 20 because of the thread interference.

Now, if we synchronize the HashMap in the same Java example using Collections.synchronizedMap() method.

Output

Now the size of Map is 20 every time.

Using ConcurrentHashMap

Other than synchronizing HashMap, another option to have a thread safe HashMap is to use ConcurrentHashMap in Java. Let’s see the same example as above using ConcurrentHashMap.

Output

That’s all for the topic How to Synchronize HashMap in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.