Copy-On-Write is considered as one of the good practices in concurrency scenarios. However, I am not clear on how it is different from a simple lock /synchronized on the write method. Could anyone help explain this?
Copy-On-Write:
public V put(K key, V value) {
synchronized (this) {
Map<K, V> newMap = new HashMap<K, V>(internalMap);
V val = newMap.put(key, value);
internalMap = newMap;
return val;
}
}
Direct lock / synchronized:
public V put(K key, V value) {
synchronized (this) {
internalMap.put(key, value);
}
}
For write threads, they are mutually excluded in above 2 examples, same.
For read threads, in Copy-On-Write, read actions after "internalMap = newMap" is run will get the updated value. And in Direct lock, read actions after "internalMap.put(key, value)" is run will get the updated value, kind of same.
So why are we promoting Copy-On-Write? Why we have to "copy" when write?