简体   繁体   中英

Difference between Copy-On-Write and Compare-Then-Swap?

I am learning about Java Concurrent Collections ( java.util.concurrent ) and the underlying techniques used. I stumbled upon Copy-On-Write and Compare-And-Swap.

I cannot quite understand what is the difference between those two. Or are both somehow used together?

Both are concurrent collections, but they use different mechanisms.

Copy-on-write collections use an effectively immutable array, and any modification creates a new array. They use synchronization briefly, during the creation of the new array. They are good if reads greatly predominate write operations.

Conversely, some other concurrent collections use Compare-And-Swap (so called CAS) mechanism for concurrency control. That is built based on low level CPU instructions which is a fundamental improvement on traditional synchronization.

A very commonly occurring patterns in programs and concurrent algorithms is the "check then act" in compare and swap the java.util.concurrent.atomic package provide atomic operation which is non blocking.

private AtomicBoolean locked = new AtomicBoolean(false);
    public boolean lock() {
        return locked.compareAndSet(false, true);
    }

Internally it will check old value and if not changed update with new value. In Other case CopyOnWriteArrayListlike a thread-safe variant of java.util.ArrayList in which all mutative operations add and set and so on are implemented by making a fresh copy of the underlying array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM