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");
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);
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With