Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Hashtable and Collections.synchronizedMap(HashMap)

As far as I know, java.util.Hashtable synchronizes each and every method in the java.util.Map interface, while Collections.synchronizedMap(hash_map) returns a wrapper object containing synchronized methods delegating calls to the actual hash_map (correct me if I am wrong).

I have two questions :

  1. What difference does it make to synchronize each and every method and to have a wrapper class? What are the scenarios to choose one over the other?

  2. What happens when we do Collections.synchronizedMap(hash_table)? Will this be equal to simply using a normal java.util.Hashtable?

like image 547
Vinoth Kumar C M Avatar asked Jan 16 '12 04:01

Vinoth Kumar C M


2 Answers

One more difference that I can find at the implementation of both the classes is as follows:

• The Hashtable class has all its methods synchronized i.e. the locking is done at the method level and hence one can say that the mutex is always at the Hashtable object (this) level.

• The method Collections.synchronizedMap(Map) returns an instance of SynchronizedMap which is an inner class to the Collections class. This class has all its methods in a Synchronized block with a mutex. The difference lies in the mutex here. The inner class SynchronizedMap has two constructors, one which takes only Map as an argument and another which takes a Map and an Object (mutex) as an argument. By default if one uses the first constructor of passing only a Map, this is used as a mutex. Though, the developer is allowed to pass another object of mutex as a second argument by which the lock on the Map methods would be only on that Object and hence less restrictive than Hashtable.

• Hence, Hashtable uses method level synchronization but Collections.synchronizedMap(Map) provides a flexibility to developer lock on provided mutex with Synchronized block.

like image 137
mankadnandan Avatar answered Sep 24 '22 22:09

mankadnandan


Here are the answers I've gotten from a bit of (hopefully correct) research:

  1. Both provide the same degree of synchronization. If you were to wrap Hashtable through Collections.synchronized you would have the same degree, but with another redundant layer, of synchronization.

  2. The main difference between Hashtable and Collections.synchronizedMap(HashMap) exist more at the API level. Because Hashtable is part of Java's legacy code, you'll see that the Hashtable API is enhanced to implement the Map interface, to become part of Java's collections framework. This means that if you were to wrap Hashtable through Collections.synchronizedMap(), the API of the wrapped Hashtable would become limited to the Map API. So if the API of Hashtable is encompassed in your definition of behavior, then it is obviously altered/limited.

like image 32
Nadir Muzaffar Avatar answered Sep 24 '22 22:09

Nadir Muzaffar