Question

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()?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top