ZohebSiddiqui
ZohebSiddiqui

Reputation: 211

Difference between Collections.synchronizedMap() and synchronized

if i create map

Map map=new HashMap(40,.75f);

synchronizing it in following two different ways

Collections.synchronizedMap(map) :- which is internally using mutex
synchronized(map){}

what is the difference between the two above approaches.

Upvotes: 1

Views: 263

Answers (2)

Gray
Gray

Reputation: 116878

Collections.synchronizedMap(map) :- which is internally using mutex
synchronized(map){}

what is the difference between the two above approaches.

The difference is that Collections.synchronizedMap(map) is doing the synchronization for you by wrapping the map in a synchronized object. If you look at the Java source for Collections class, you should see the SynchronizedMap object. In there it does stuff like:

final Object      mutex;        // Object on which to synchronize
...
public int size() {
   synchronized (mutex) {return m.size();}
}

So internally it is doing the same as you calling synchronized externally. However, it takes the guess work and programming of you doing it manually. It saves you from missing and not protecting an important method call or passing your Map to another library that doesn't properly synchronize it or something.

There is a 3rd option that may be better which is to use the ConcurrentHashMap. That is a hash-map which is written from scratch to allow multiple threads to operate on it in parallel. It will provide better performance than the two options you mention.

Upvotes: 1

Magus
Magus

Reputation: 15104

A synchronized object assure that only one thread at a time can use the object.

http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

Upvotes: 0

Related Questions