Java – How to get synchronized version of Map ?

In this article, we will discuss how to get synchronized version of Map using Collections class’s utility synchronizedMap() method

Q) How to make Synchronized Map ?

  • From original collection framework introduced in Java 1.2 version, by default HashMap, LinkedHashMap and TreeMap classes aren’t thread-safe i.e.; non-synchronized
  • But we can make it thread-safe using Collections utility synchronizedMap(map) method
  • While iterating synchronized Map, make sure to iterate inside synchronized block;
  • otherwise we may face non-deterministic behavior

From Java doc,

* It is imperative that the user manually synchronize on the returned
* map when iterating over any of its collection views:

       Map m = Collections.synchronizedMap(new HashMap());
           ...
       Set s = m.keySet();  // Needn't be in synchronized block
           ...
       synchronized (m) {  // Synchronizing on m, not s!
           Iterator i = s.iterator(); // Must be in synchronized block
           while (i.hasNext())
               foo(i.next());
       }

* Failure to follow this advice may result in non-deterministic behavior.

1. To get Synchronized version of Map

Method signature:

public static Map synchronizedMap(Map<Object> map);

SynchronizedVersionOfMap.java

package in.bench.resources.java.collection;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SynchronizedVersionOfMap {

	public static void main(String[] args) {

		// creating HashMap object of type String, String
		HashMap<String, String> unSynchronizedMap =
				new HashMap<String, String>();

		// adding elements to HashMap object
		unSynchronizedMap.put("Facebook", "Mark Zuckerberg");
		unSynchronizedMap.put("LinkedIn", "Reid Hoffman");
		unSynchronizedMap.put("YouTube", "	Steve Chen");
		unSynchronizedMap.put("Google", "Larry Page");
		unSynchronizedMap.put("Google", "Sergey Brin"); // duplicate
		unSynchronizedMap.put("Twitter", "Jack Dorsey"); 

		// to get synchronized HashMap
		Map<String, String> synchronizedMap = Collections
				.synchronizedMap(unSynchronizedMap);

		// get entries from HashMap
		Set<Entry,<String, String>> set = synchronizedMap.entrySet();

		System.out.println("Iterating through synchronized HashMap\n");

		// iterate inside synchronized block
		synchronized(synchronizedMap) {

			Iterator<Entry<String, String>> iterator = set.iterator();

			System.out.println("Company\t\tFounder Name");
			System.out.println("========\t=================");

			while (iterator.hasNext()) {
				Map.Entry<String, String> mapEntry =
						(Map.Entry<String, String>) iterator.next();
				System.out.println(mapEntry.getKey()
						+ "\t\t" + mapEntry.getValue());
			}
		}
	}
}

Output:

Iterating through synchronized HashMap

Company		Founder Name
========	=================
Google		Sergey Brin
Twitter		Jack Dorsey
LinkedIn	Reid Hoffman
Facebook	Mark Zuckerberg
YouTube		Steve Chen

Note: similarly, we can make thread-safe for LinkedHashMap or TreeMap classes

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to get synchronized version of Collection ?
Java - How to get synchronized version of Set ?