Working of Collections.synchronizedMap

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We have seen working of HashMap and Hashtable in java collections framework and know that Hashtable provides synchronized methods while HashMap doesn’t. Hashtable is thread safe and HashMap is not. But there is a way to synchronize a HashMap and make it thread safe. We can make use of Collections.synchronizedMap for a map. Collections utility class provides Collections.synchronizedXXX() methods for all sorts of collections. This article will deal with working of Collections.synchronizedMap().

Working of Collections.synchronizedMap():

  • Collections class defines a private nested static class named SynchronizedMap.
  • SynchronizedMap has two instance variables mutex and m.
  • mutex serves the purpose of a mutex variable in working of Collections.synchronizedMap and server the purpose of holding original collection.

This is how SynchronizedMap is defined roughly.

Let us try to write some sample code for SynchronizedMap

  • Note that we are passing a map created as HashMap to Collections.synchronizedMap(map);
  • It instantiates SynchronizedMap and passes m which refers to object referred by map. So, is backing map now.
  • mutex refers to current SynrozniedMap instance internally. We can see the same in source code itself.


SynchronizedMap Constructor:

Calling map.put() method:

Note that Collections.synchronizedMap returns an instance of type SynchronizedMap. so when you call map.put(1,null);  due to polymorphism, SynchronizedMap.put() method is called which is synchronized on mutex, i.e. current instance of SynchronizedMap.

Note that value is being put into original map backed by which is synchronized on mutex and in code, it is being referred by synchronizedMap reference variable as shown below.

Final Structure of Map

Final Structure of Map

So, synchronizedMap is the actual object which we will use which is created from map. synchronizedMap  is thread safe and not map. I hope the article helped understand the working of Collections.synchronizedMap() method in collections framework. In next article we will learn about ConcurrentHashMap.

Share Button

Leave a Reply

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