CAS mechanism and simple implementation

CASE:

CAS is an abbreviation of the English word Compare And Swap, which translates to compare and replace the
CAS of three basic parameters:
Memory value, estimated value and the updated value
Specific procedures:
Here Insert Picture Description
Estimated thread 2 when the variable i is read, the read value is 0, but this time into a thread 1 i 1, i is 1. The main memory so the memory and estimate the value is not the same need to re read during the operation.
When the memory is not the same value and the estimated value of time, it will cancel the operation, re-read, to ensure consistent variables
we simply use the following code to achieve what CAS:

package com.jym.thread;

import java.util.Random;

/**
 * @program: thread
 * @description: CAS学习
 * @author: jym
 * @create: 2020/01/28
 */
public class JymCASTest {
    public static void main(String[] args) {
        final JymCAS jymCAS = new JymCAS();
        for (int i =0;i<10;i++){
            new Thread(new Runnable() {
                public void run() {
                    //获取内存值
                    int expectValue = jymCAS.getValue();
                    System.out.println(expectValue);
                    boolean flag = jymCAS.compilerAndSet(expectValue, new Random().nextInt(100));
                    System.out.println(flag);
                }
            }).start();
        }
    }
}

class JymCAS {
    private int value;

    public int getValue() {
        return value;
    }

    public synchronized int compilerAndSwap(int expectValue ,int newValue){
        int oldValue = this.value;
        // 内存值与预期值一样,进行赋值操作
        if(oldValue==expectValue){
            this.value = newValue;
        }
        return oldValue;
    }

    // 当预期值与内存值相等,说明赋值成功了
    public boolean compilerAndSet(int expectValue ,int newValue){
        return expectValue==compilerAndSwap(expectValue,newValue);
    }
}

Lack of study time, too shallow knowledge, that's wrong, please forgive me.

There are 10 kinds of people in the world, one is to understand binary, one is do not understand binary.

Published 71 original articles · won praise 54 · views 420 000 +

Guess you like

Origin blog.csdn.net/weixin_43326401/article/details/104102983