自旋鎖的洋名叫spin lock,是一種比較有個性的鎖,由於它站在傳統的互斥鎖的對立面。若是併發時,互斥鎖的作法是讓線程阻塞,但自旋鎖卻不這麼作,而是原地打轉,不停的去搶鎖,搶不到誓不罷休。簡而言之,互斥鎖是重量級(悲觀)鎖,自旋鎖是輕量級(樂觀)鎖。自旋鎖使用場景是:一、多核處理器,二、線程等待鎖的時間很短,短到比線程兩次上下文切換時間還少,說白了就是鎖裏操做的事情很簡單。java
如何實現自旋鎖呢?唯有CAS。何謂CAS?它的洋名叫Compare And Swap,簡單來講就是比較並交換。該算法涉及三個數:內存值V,舊的預期值A,新的預期值B。當且僅當舊的預期值A和內存值V相同時,將內存值改成B,不然什麼也不作。算法
CAS 是實現自旋鎖的基礎(也是實現樂觀鎖的基礎),CAS 利用 CPU 指令保證了操做的原子性,以達到鎖的效果。先看個JDK實例:多線程
public class CountDownLatch { /** * Synchronization control For CountDownLatch. * Uses AQS state to represent count. */ private static final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 4982264981922014374L; Sync(int count) { setState(count); } int getCount() { return getState(); } protected int tryAcquireShared(int acquires) { return (getState() == 0) ? 1 : -1; } protected boolean tryReleaseShared(int releases) { // Decrement count; signal when transition to zero for (;;) { int c = getState(); if (c == 0) return false; int nextc = c-1; if (compareAndSetState(c, nextc)) return nextc == 0; } } } private final Sync sync; /** * Constructs a {@code CountDownLatch} initialized with the given count. * * @param count the number of times {@link #countDown} must be invoked * before threads can pass through {@link #await} * @throws IllegalArgumentException if {@code count} is negative */ public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); this.sync = new Sync(count); } /** * Causes the current thread to wait until the latch has counted down to * zero, unless the thread is {@linkplain Thread#interrupt interrupted}. * * <p>If the current count is zero then this method returns immediately. * * <p>If the current count is greater than zero then the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of two things happen: * <ul> * <li>The count reaches zero due to invocations of the * {@link #countDown} method; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * @throws InterruptedException if the current thread is interrupted * while waiting */ public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } /** * Causes the current thread to wait until the latch has counted down to * zero, unless the thread is {@linkplain Thread#interrupt interrupted}, * or the specified waiting time elapses. * * <p>If the current count is zero then this method returns immediately * with the value {@code true}. * * <p>If the current count is greater than zero then the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of three things happen: * <ul> * <li>The count reaches zero due to invocations of the * {@link #countDown} method; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>The specified waiting time elapses. * </ul> * * <p>If the count reaches zero then the method returns with the * value {@code true}. * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the specified waiting time elapses then the value {@code false} * is returned. If the time is less than or equal to zero, the method * will not wait at all. * * @param timeout the maximum time to wait * @param unit the time unit of the {@code timeout} argument * @return {@code true} if the count reached zero and {@code false} * if the waiting time elapsed before the count reached zero * @throws InterruptedException if the current thread is interrupted * while waiting */ public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } /** * Decrements the count of the latch, releasing all waiting threads if * the count reaches zero. * * <p>If the current count is greater than zero then it is decremented. * If the new count is zero then all waiting threads are re-enabled for * thread scheduling purposes. * * <p>If the current count equals zero then nothing happens. */ public void countDown() { sync.releaseShared(1); } /** * Returns the current count. * * <p>This method is typically used for debugging and testing purposes. * * @return the current count */ public long getCount() { return sync.getCount(); } /** * Returns a string identifying this latch, as well as its state. * The state, in brackets, includes the String {@code "Count ="} * followed by the current count. * * @return a string identifying this latch, as well as its state */ public String toString() { return super.toString() + "[Count = " + sync.getCount() + "]"; } }
看上面標紅那裏,就是自旋鎖實現的關鍵:一、無限循環;二、CAS。接下來再看自旋鎖的實現與應用場景:併發
package com.wulinfeng.test.testpilling.util; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; /** * 自旋鎖 * * @author wulinfeng * @version C10 2018年12月21日 * @since SDP V300R003C10 */ public class SpinLock implements Lock { // 利用AtomicBoolean來調用CAS,ab初始(內存)值是false private AtomicBoolean ab = new AtomicBoolean(false); @Override public void lock() { /* * getAndSet將ab設置爲true,並返回ab以前(內存)的值。 * 由於ab的初始(內存)值就是false,因此第一個線程不會進入循環,也就是說它搶到了鎖 * 然後面的線程來的時候,內存值已是true,將進入循環自旋 */ while (ab.getAndSet(true)) { } } @Override public void unlock() { // 將內存值從新設置爲false ab.set(false); } @Override public void lockInterruptibly() throws InterruptedException { // TODO Auto-generated method stub } @Override public boolean tryLock() { // TODO Auto-generated method stub return false; } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { // TODO Auto-generated method stub return false; } @Override public Condition newCondition() { // TODO Auto-generated method stub return null; } }
測試代碼:app
package com.wulinfeng.test.testpilling; import java.util.concurrent.CountDownLatch; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.wulinfeng.test.testpilling.util.SpinLock; import junit.framework.TestCase; public class SpinLockTest { // 開始時間 private long startTime = 0L; // 計數器 private int count = 0; // 讓Junit支持多線程,10個線程就先初始化10 private CountDownLatch latch = new CountDownLatch(10); @Before public void before() { startTime = System.currentTimeMillis(); } @After public void after() { System.out.printf("count值:%d, 耗時:%d毫秒.\n", count, System.currentTimeMillis() - startTime); } @Test public void testSpinLock() { // 初始化自旋鎖 SpinLock sl = new SpinLock(); for (int i = 0; i < 10; i++) { new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 1000; j++) {
// 加鎖
sl.lock();
// 自增 count++;
// 解鎖
sl.unlock(); } // 一個線程執行完了就減1,10個線程執行完了就變成0,執行主線程 latch.countDown(); } }).start(); } // 主線程等待 try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } TestCase.assertEquals(count, 10000); } }
輸出結果:less
count值:10000, 耗時:9毫秒.