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?
One benefit in this example is that you get snapshot semantics for the copy on write case: every reference to internalMap
is immutable and will not change anymore once obtained. This can be beneficial when you have many concurrent read operations traversing internalMap
and only occasional updates.
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