当前位置:网站首页>Have you encountered ABA problems? Let's talk about the following in detail, how to avoid ABA problems

Have you encountered ABA problems? Let's talk about the following in detail, how to avoid ABA problems

2022-07-06 13:39:00 Wake up duck, did you program today?

1、 There are two threads modifying the value of a variable at the same time , Threads 1、 Threads 2, Update variable values , Change variables from A Updated to B

2、 The first thread 1 To obtain CPU Time slice , Threads 2 Wait for some reason , Threads 1 Compare and update ,CAS
(CompareAndSwap), Successfully changed the value of the variable from A Update to B

3、 After updating , There happens to be another thread 3 Come in and want to change the value of the variable from B Update to A, Threads 3 Compare and update , Successfully changed the value of the variable from B Updated to A

4、 Threads 2 To obtain CPU Time slice , Then compare and update , The value found is expected A, And then it's updated B, But threads 1 I don't know that the value has changed from A-->B-->A This process , This is it. ABA problem .

 

How to avoid ABA problem ?

It can be solved by adding version number or timestamp , Or guarantee one-way increasing or decreasing, there will be no such problems ,atomic Under bag AtomicStampedReference Class CompareAndSet Method first checks whether the current reference is equal to the expected reference , And whether the current flag is equal to the expected flag , If all are equal , Then set the value of this flag to the given update value in an atomic way

package com.ws.cas;

import java.util.concurrent.atomic.AtomicInteger;

public class CASDemo {

    //CAS compareAndSet: Compare and exchange !!!
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2020);

        // For what we usually write SQL Come on : Optimism lock !
        // The first parameter is expectation 、 The second parameter is update 
        //public final boolean compareAndSet(int expect, int update)
        // If my expectations reach , Then update , Otherwise, it will not be updated  CAS yes CPU The concurrent primitives of 


        // Mess with threads 
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());

        System.out.println(atomicInteger.compareAndSet(2021, 2020));
        System.out.println(atomicInteger.get());

        // Expected thread 
        System.out.println(atomicInteger.compareAndSet(2020, 6666));
        System.out.println(atomicInteger.get());



    }
}

CAS Other problems caused ?

  1. Only one atomic operation of shared variables can be guaranteed
  2. The spin CAS If it doesn't work for a long time , Will give CPU Bring the problem of high cost
原网站

版权声明
本文为[Wake up duck, did you program today?]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916452404.html