Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Copy-On-Write is different from a direct lock / synchronized on write method?

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?

like image 830
Scott Cheung Avatar asked Jan 01 '23 21:01

Scott Cheung


1 Answers

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.

like image 180
michid Avatar answered Jan 08 '23 02:01

michid