CAS algorithms, variables atoms

1, CAS algorithm

  • CAS (Compare-And-Swap) is a hardware support for concurrent processors for multiprocessor designed to operate in a special command for managing concurrent access to shared data.
  • CAS is to achieve non-blocking algorithm for a lock-free;
  • CAS includes three operands, V needs to read memory values, comparison values ​​A, B intends to write a new value;
  • If and only if the value is equal to V A, CAS B with a new value by updating the value of V atomic manner, it would not do anything;
CAS simulation algorithm
/**
 * @author zhengzheng046
 */
public class TestCompareAndSwap {

    public static void main(String[] args) {
        final CompareAndSwap compareAndSwap = new CompareAndSwap();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                int expectvalue = compareAndSwap.get();
                boolean b = compareAndSwap.compareAndSet(expectvalue, (int) (Math.random() * 101));
                System.out.println("[" + b + "]");
            }).start();
        }
    }
}


class CompareAndSwap {

    private int value;

    public synchronized int get() {
        return value;
    }

    /**
     * 比较,旧值与期望值相等时,将新值赋给旧值变量
     *
     * @param expectValue
     * @param newValue
     * @return
     */
    public synchronized int compareAndSwap(int expectValue, int newValue) {
        int oldValue = value;
        if (oldValue == expectValue) {
            this.value = newValue;
        }
        return oldValue;
    }

    //设置
    public synchronized boolean compareAndSet(int expectValue, int newValue) {
        return expectValue == compareAndSwap(expectValue, newValue);
    }
}
Published 21 original articles · won praise 4 · Views 515

Guess you like

Origin blog.csdn.net/weixin_39617728/article/details/104807145