HashMap Sync

I have a card, and I synchronize it between them. Will there be any differences in the behavior of the card when inserted after synchronization?

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"); 
+4
source share
8 answers

Insertions after calling Collections.synchronizedMap(myMap); would be thread safe, inserts would not be thread safe before. All Collections.synchronizedMap(myMap); - This is transferring your map object to a thread-safe SynchronizedMap object. Other than that, there is no difference.

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

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

Returns a synchronized (thread safe) card supported by the specified card. In order to guarantee consistent access, it is imperative that all access to the support card is through the returned card.

It is imperative that the user manually synchronizes on the returned map when repeating any of their 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 comply with this advice may result in non-deterministic behavior.

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

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

+4
source

It will behave exactly like the card in front of it, except that it will be synchronized. You should use the return value Collections.synchronizedMap(myMap); but since the myMap parameter myMap not be changed.

+2
source

Do you consider using ConcurrentHashMap from java.util.concurrent?

In principle, this is more or less a substitution reduction for HashMap, but when used in a thread it is safe, it has additional guaranteed atomic methods for certain tasks and without blocking (by using properties a reasonable hash function) in most cases.

+1
source

No difference.

Collections.synchronizedMap() simply a forward HashMap .

0
source
 Collections.synchronizedMap(myMap); 

You ignored the return value. Use as

  Map syncMap = Collections.synchronizedMap(myMap); // wrapper 
0
source

Yes, the HashMap not synchronized, so inserting elements from parallel threads gives undefined results. Using a synchronized card prevents this.

0
source

The Collections.synchronizedMap(Map) method creates a new synchronized map supported by the map you are submitting. Therefore, it does NOT synchronize the myMap card.

0
source

Source: https://habr.com/ru/post/1347523/


All Articles