RCS
RCS

Reputation: 1432

What is difference between HashMap in synchronized block vs Collections.synchronizedMap().

What is difference between HashMap in synchronized block vs Collections.synchronizedMap().

HashMap<String,String> hm = new HashMap<String,String>();
hm.put("key1","value1");
hm.put("key2","value2");
synchronized(hm)
{
   // Thread safe operation
}

Map<String, String> synchronizedMap = Collections.synchronizedMap(hm);
// Use synchronizedMap for Thread safe concurrent operation 

Which is better out of these two?

Upvotes: 2

Views: 528

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96385

Using the synchronizedMap method is more convenient and safer in that you know all accesses to the map will be protected (as long as you don't bypass it by calling methods on hm directly).

But using the synchronized block gives you the ability to control the granularity of locking, by holding the lock over multiple statements, which the synchronizedMap option doesn't allow for.

So if you need multiple statements to be executed without being interleaved with calls from other threads, you would have to choose the synchronized blocks (or else switch to something like ConcurrentHashMap if you're looking for something like putIfAbsent or similar functionality). If you don't need that, the synchronizedMap is easier.

Upvotes: 2

NRitH
NRitH

Reputation: 13893

They're the same. synchronizedMap() is far easier than handling the syncing yourself, though.

Upvotes: 1

Related Questions