当前位置:网站首页>Spin lock using CAS

Spin lock using CAS

2022-06-23 16:05:00 weixin_ forty-three million seven hundred and sixty-six thousan

1. Spin lock concept

  • spinlocks (spinlock): When a thread is acquiring a lock , If the lock has been acquired by another thread , Then the thread will wait in a loop , And then constantly judge whether the lock can be successfully acquired , Loop will not exit until lock is acquired .

2. Write spin lock

import java.util.concurrent.atomic.AtomicBoolean;
// spinlocks 
public class SpinLock {
    
    //CAS
    private AtomicBoolean cas = new AtomicBoolean(false);
    // Lock holder thread 
    private Thread spinLockOwnerThread = null;

    public void lock(){
    

        while (!cas.compareAndSet(false,true))
        {
    
            //CAS The spin 
        }
        spinLockOwnerThread = Thread.currentThread();
    }

    public void unLock(){
    
        // The current thread is equal to the thread that holds the lock before unlocking 
        if (Thread.currentThread()==spinLockOwnerThread)
        {
    
            spinLockOwnerThread = null;
            cas.set(false);
            // The last set CAS The value of is false, Why? ?
            // If you execute first cas.set(false), Here comes a new thread ,
            // It's been a success CAS Of compareAndSet,
            // take  spinLockOwnerThread  Point to Thread.currentThread();
            // Finally, we will carry out spinLockOwnerThread = null;
            // This will cause the last thread holding the lock to fail to unlock 
            // That is to say, it is impossible to pass through Thread.currentThread()==spinLockOwnerThread Judge 
            // This causes the program to block all the time 
           
        }
    }
}

3. Test the spin lock

class Test {
    
    // Introduce spin lock 
    private static final SpinLock spinLock = new SpinLock();

    public static void main(String[] args) {
    
        Thread t1  = new Thread(Test::run,"t1");
        Thread t2  = new Thread(Test::run,"t2");
        Thread t3  = new Thread(Test::run,"t3");
        Thread t4  = new Thread(Test::run,"t4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

    public static void run(){
    
        spinLock.lock();
        System.out.println(Thread.currentThread().getName());
        try 
        {
    
            Thread.sleep(5000);
        } 
        catch (InterruptedException e) 
        {
    
            e.printStackTrace();
        }
        finally
        {
    
          spinLock.unLock();
        }
      
    }
}
原网站

版权声明
本文为[weixin_ forty-three million seven hundred and sixty-six thousan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231525148212.html