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


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())

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


Example: To get Synchronized version of Map

Method signature:

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


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

		// 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");

			while (iterator.hasNext()) {
				Map.Entry<String, String> mapEntry = 
						(Map.Entry<String, String>);
						+ "\t\t" + mapEntry.getValue());


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




Happy Coding !!
Happy Learning !!

How to get synchronized version Collection
How to get synchronized version of Set