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 :
-
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?
-
What happens when we do
Collections.synchronizedMap(hash_table)
? Will this be equal to simply using a normaljava.util.Hashtable
?
Best Answer
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 theHashtable
object (this
) level.• The method
Collections.synchronizedMap(Map)
returns an instance ofSynchronizedMap
which is an inner class to theCollections
class. This class has all its methods in aSynchronized
block with a mutex. The difference lies in the mutex here. The inner classSynchronizedMap
has two constructors, one which takes onlyMap
as an argument and another which takes aMap
and anObject
(mutex) as an argument. By default if one uses the first constructor of passing only aMap
,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 theMap
methods would be only on thatObject
and hence less restrictive thanHashtable
.• Hence,
Hashtable
uses method level synchronization butCollections.synchronizedMap(Map)
provides a flexibility to developer lock on provided mutex withSynchronized
block.