Java thread safety - spin lock

Author: pheasant

 锁作为并发共享数据,保证一致性的工具,在JAVA平台有多种实现(如 synchronized 和 ReentrantLock等等 ) 。这些已经写好提供的锁为我们开发提供了便利,但是锁的具体性质以及类型却很少被提及。本系列文章将分析JAVA下常见的锁名称以及特性,为大家答疑解惑。

1. Spin lock

The spin lock is implemented by allowing the current thread to continuously execute in the loop body, and the critical section can only be entered when the conditions of the loop are changed by other threads. as follows

public class SpinLock {

  private AtomicReference<Thread> sign =new AtomicReference<>();

  public void lock(){
    Thread current = Thread.currentThread();
    while(!sign .compareAndSet(null, current)){
    }
  }

  public void unlock (){
    Thread current = Thread.currentThread();
    sign .compareAndSet(current, null);
  }
}

Using the CAS atomic operation, the lock function sets the owner to the current thread and predicts that the original value is null. The unlock function sets the owner to null, and the predicted value is the current thread.

When a second thread calls the lock operation, because the owner value is not empty, the loop is always executed until the first thread calls the unlock function to set the owner to null, and the second thread can enter the critical section.

Since the spin lock just keeps the current thread executing the loop body without changing the thread state, the response speed is faster. But when the number of threads keeps increasing, the performance drops significantly, because each thread needs to be executed, occupying CPU time. The period of time if the thread contention is not intense and the lock is held. Suitable for use with spinlocks.

Note: This example is an unfair lock, and the order in which the locks are obtained will not be carried out in the order in which the locks are entered.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325710653&siteId=291194637