Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap synchronisation

Tags:

java

I have a map and i am synchronising it in between.Will there be any difference in behaviour of the map in insertion after the synchronisation?

HashMap<String,String> myMap = new HashMap<String,String>();
myMap.put("abc","123");
myMap.put("efg","456");
Collections.synchronizedMap(myMap);
myMap.put("hij","789");
myMap.put("jkl","234");
like image 990
Ammu Avatar asked Dec 22 '22 15:12

Ammu


2 Answers

The insertions after calling Collections.synchronizedMap(myMap); would be thread safe, insertions before would not be thread safe. All Collections.synchronizedMap(myMap); does is wrap your map object in a thread-safe SynchronizedMap object. Other than that there is no difference.

Also, you need to change the code to myMap = Collections.synchronizedMap(myMap);

like image 122
Nishan Avatar answered Dec 24 '22 05:12

Nishan


<K, V> Map<K, V> java.util.Collections.synchronizedMap(Map<K, V> m)

Returns a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.

It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:

Map m = Collections.synchronizedMap(new HashMap());
   ...
Set s = m.keySet();  // Needn't be in synchronized block
  ...
synchronized(m) {  // Synchronizing on m, not s!
  Iterator i = s.iterator(); // Must be in synchronized block
  while (i.hasNext())
      foo(i.next());
}

Failure to follow this advice may result in non-deterministic behavior.

The returned map will be serializable if the specified map is serializable.

Parameters: m the map to be "wrapped" in a synchronized map. Returns: a synchronized view of the specified map.

like image 26
Marcin Avatar answered Dec 24 '22 05:12

Marcin