Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Normal Map and collections.synchronizedmap

In some android open source code I found

 private Map<ImageView, String> imageViews=Collections.synchronizedMap(new
 WeakHashMap<ImageView, String>());

can any one explain me difference between Normal Map and collections.synchronizedmap

like image 885
user1442034 Avatar asked Jan 22 '13 06:01

user1442034


2 Answers

The regular Map implementations in java.util package are not thread safe. This means that if multiple threads are doing get() or put() operations on the same Map, it may result in race conditions or inconsistent data in the Map.

To use an existing Map in a multi-threaded environment, you can get a synchronized instance of the same by calling Collections.synchronizedMap(). On such instances, most of the methods like get(), put and keyset() are synchronized and can be safely used concurrently.
For more information on this, refer to http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map)

like image 147
Akhil Raina Avatar answered Sep 29 '22 22:09

Akhil Raina


We are using "Synchronized" to ensure that two concurrently-executing threads or processes do not execute specific portions of a program at the same time.

like image 35
Manoj Pal Avatar answered Sep 29 '22 23:09

Manoj Pal