简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM