Does the synchronizedMap method in Collections synchronize both read and write operations [duplicate]

StackOverflow https://stackoverflow.com/questions/18241403

Domanda

When i do a Collections.synchronizedMap(someHashMap), are all access to the map synchronized? Or only write operations (put) synchronized? How about if two threads are reading from the Map? Will it be synchronized? DOesnt seem necessary How abotu if one thread is doing put() and another is doing get()?

È stato utile?

Soluzione

Look at the source code of SynchronizedMap that's wrapping your Map.

...
public V get(Object key) {
    synchronized (mutex) {return m.get(key);}
}

public V put(K key, V value) {
    synchronized (mutex) {return m.put(key, value);}
}
public V remove(Object key) {
    synchronized (mutex) {return m.remove(key);}
}
... // more methods synchronized in the same way

From

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
    return new SynchronizedMap<>(m);
}

So, yes, all accesses are synchronized.

Altri suggerimenti

Yes, it synchronizes all operations. It doesn't use a multi-reader, single-writer approach - it's just as simple as synchronizing all access through a single monitor.

Both reads and writes are synchronised, which is necessary to ensure visibility.

All method calls on the collection are synchronized. Only one thread will be allowed to read/modify the collection at a time.

The synchronized* methods from Collections are not designed to be the best thread safe version/implementations. They are just suppose to be convenient.

Synchronization is a difficult problem and usually requires different synchronization approaches based on your specific scenario. If you require other types of thread-safety, there are lots of other thread safe collections available. You can also write the synchronization logic yourself.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top