深入理解獨佔鎖ReentrantLock類鎖

 ReentrantLock介紹

【1】ReentrantLock是一種基於AQS框架的應用實現,是JDK中的一種線程並發訪問的同步手段,它的功能類似於synchronized是一種互斥鎖,可以保證線程安全。

【2】相對於 synchronized, ReentrantLock具備如下特點:

1)可中斷 
2)可以設置超時時間
3)可以設置為公平鎖 
4)支持多個條件變量
5)與 synchronized 一樣,都支持可重入

 

ReentrantLock問題分析

【1】ReentrantLock公平鎖和非公平鎖的性能誰更高?

  1)那肯定是非公平鎖,但是為什麼是非公平更高呢?

  2)因為涉及到了線程的park()與unpark()操作,不管是ReentrantLock還是synchronized,都在避免這些操作。

    (1)如ReentrantLock的非公平同步器在得不到鎖的情況下,即將要進入之前會再加一次鎖,生成節點之後又會加一次鎖,把節點放入隊列之後又會加一次鎖,最終迫不得已才會進行park()操作。

    (2)如synchronized,在生成monitor的過程之中也會多次嘗試加鎖,避免monitor的生成。

  3)為什麼要避免呢?這就涉及到線程的概念了。

    (1)因為park()與unpark()操作涉及到了線程的上下文切換,同時又涉及到了時間片輪轉機制

    (2)線程上下文切換,需要將舊的線程資源保存回內存【保存執行到了哪一步,需要什麼東西】,將新的線程的資源加載入CPU,讓新線程具備執行的資源並開始執行。但是這些操作都是需要花費時間的,會消耗一部分時間片的資源。如(這裡僅僅只是舉例說明),一個時間片本來就是50s,你拿到的時候花費了一定的時間(如10s)進行上下文切換,現在剛執行不到5s,你又要進行一次切換(又要花費10s)。那下一個拿到時間片的線程會不會還是會繼續切換呢?而且你要下次運行就又要等時間片了。

    (3)所以說,本質上非公平機制是為了讓持有CPU的線程儘可能多的做有用的任務,減少上線下文切換帶來的開銷,畢竟時間片來之不易,本身就是從眾多線程之中好不容易分配得來的。

 

ReentrantLock的使用

【1】使用模板

Lock lock = new ReentrantLock();
//加鎖
lock.lock();
try {
    // 臨界區代碼
    // TODO 業務邏輯:讀寫操作不能保證線程安全
} finally {
    // 解鎖,放置在這裡的原因是保證異常情況都不能干擾到解鎖邏輯
    lock.unlock();
}

 

【2】可重入的嘗試

public class ReentrantLockDemo {
    public static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        method1();
    }
    public static void method1() {
        lock.lock();
        try {
            log.debug("execute method1");
            method2();
        } finally {
            lock.unlock();
        }
    }
    public static void method2() {
        lock.lock();
        try {
            log.debug("execute method2");
            method3();
        } finally {
            lock.unlock();
        }
    }
    public static void method3() {
        lock.lock();
        try {
            log.debug("execute method3");
        } finally {
            lock.unlock();
        }
    }
}

 

【3】中斷機制嘗試

  進行說明:這裏面其實是main線程先獲得了鎖,所以t1線程其實是先進入隊列裏面,然後在main線程裏面將t1設置為了中斷。當main線程釋放鎖的時候,t1去加鎖,發現自己被中斷了,所以拋出中斷異常,退出加鎖。【其實這個中斷加鎖,怎麼說,就是可以讓失去加鎖的權利,但是不影響你去排隊】

@Slf4j
public class ReentrantLockDemo {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {

            log.debug("t1啟動...");

            try {
                lock.lockInterruptibly();
                try {
                    log.debug("t1獲得了鎖");
                } finally {
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("t1等鎖的過程中被中斷");
            }

        }, "t1");
        
        lock.lock();
        try {
            log.debug("main線程獲得了鎖");
            t1.start();
            //先讓線程t1執行
            Thread.sleep(10000);

            t1.interrupt();
            log.debug("線程t1執行中斷");
        } finally {
            lock.unlock();
        }

    }

}

 

【4】鎖超時嘗試

@Slf4j
public class ReentrantLockDemo {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {

            log.debug("t1啟動...");
            //超時
            try {
                // 注意: 即使是設置的公平鎖,此方法也會立即返回獲取鎖成功或失敗,公平策略不生效
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.debug("等待 1s 後獲取鎖失敗,返回");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }

            try {
                log.debug("t1獲得了鎖");
            } finally {
                lock.unlock();
            }

        }, "t1");


        lock.lock();
        try {
            log.debug("main線程獲得了鎖");
            t1.start();
            //先讓線程t1執行
            Thread.sleep(2000);
        } finally {
            lock.unlock();
        }

    }

}

 

【5】條件變量的嘗試

  說明:

    1)java.util.concurrent類庫中提供Condition類來實現線程之間的協調。調用Condition.await() 方法使線程等待,其他線程調用Condition.signal() 或 Condition.signalAll() 方法喚醒等待的線程。

    2)由於可控的原因我們甚至可以多個條件隊列來進行對線程調控。

  注意:調用Condition的await()和signal()方法,都必須在lock保護之內

@Slf4j
public class ReentrantLockDemo {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition cigCon = lock.newCondition();
    private static Condition takeCon = lock.newCondition();

    private static boolean hashcig = false;
    private static boolean hastakeout = false;

    //送煙
    public void cigratee(){
        lock.lock();
        try {
            while(!hashcig){
                try {
                    log.debug("沒有煙,歇一會");
                    cigCon.await();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            log.debug("有煙了,幹活");
        }finally {
            lock.unlock();
        }
    }

    //送外賣
    public void takeout(){
        lock.lock();
        try {
            while(!hastakeout){
                try {
                    log.debug("沒有飯,歇一會");
                    takeCon.await();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            log.debug("有飯了,幹活");
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo6 test = new ReentrantLockDemo6();
        new Thread(() ->{
            test.cigratee();
        }).start();

        new Thread(() -> {
            test.takeout();
        }).start();

        new Thread(() ->{
            lock.lock();
            try {
                hashcig = true;
                log.debug("喚醒送煙的等待線程");
                cigCon.signal();
            }finally {
                lock.unlock();
            }


        },"t1").start();

        new Thread(() ->{
            lock.lock();
            try {
                hastakeout = true;
                log.debug("喚醒送飯的等待線程");
                takeCon.signal();
            }finally {
                lock.unlock();
            }


        },"t2").start();
    }

}

 

 

ReentrantLock源碼分析(版本為jdk14)

【0】前置部分最好有關於JDK實現管程的了解【可查看  深入理解AQS–jdk層面管程實現

【1】ReentrantLock類自身部分

  0)繼承關係

//鎖的接口定義,定義了一個鎖該具備哪一些功能
public interface Lock {

    void lock();

    void lockInterruptibly() throws InterruptedException;

    boolean tryLock();

    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

    void unlock();

    Condition newCondition();
}

  1)屬性值

//同步器句柄,同步器提供了所有的實現機制
private final Sync sync;

  2)構造方法

//默認是採用非公平的同步器
public ReentrantLock() {
    sync = new NonfairSync();
}

//此外可以根據傳入的參數選擇同步器
public ReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
}

  3)其他方法【看完之後,你會發現,其實ReentrantLock什麼事都不幹,統統都交給了持有的AQS同步器去幹活了,有一種修飾器設計模式的味道,只是包裝了一下,具體內部的同步器類型由自己選擇,所以同步器顯得就很重要

public class ReentrantLock implements Lock, java.io.Serializable {
    .....
    //獲取鎖定
    public void lock() {
        sync.lock();
    }

    //中斷式的加鎖,如果沒有被中斷就會加鎖
    public void lockInterruptibly() throws InterruptedException {
        sync.lockInterruptibly();
    }

    //僅當在調用時鎖不被另一個線程持有時才獲取鎖
    public boolean tryLock() {
        return sync.tryLock();
    }
   //超時加鎖,限定加鎖時間
    public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
        return sync.tryLockNanos(unit.toNanos(timeout));
    }

    //嘗試釋放此鎖
    public void unlock() {
        sync.release(1);
    }

    //返回一個用於此鎖定實例的條件實例,說白了就是監視器
    public Condition newCondition() {
        return sync.newCondition();
    }

    //查詢當前線程在此鎖上保留的數量
    public int getHoldCount() {
        return sync.getHoldCount();
    }

    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

    //判斷同步器是否在被持有狀態,也就是被加鎖了
    public boolean isLocked() {
        return sync.isLocked();
    }

    //判斷同步器的類型
    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    protected Thread getOwner() {
        return sync.getOwner();
    }

    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    //判斷同步器裏面是否有該線程
    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    public boolean hasWaiters(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    //返回條件隊列裏面等待的線程的個數
    public int getWaitQueueLength(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    //返回條件隊列裏面等待的線程
    protected Collection<Thread> getWaitingThreads(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
    }


}

 

【2】抽象的Sync類部分

abstract static class Sync extends AbstractQueuedSynchronizer {
    //定義了核心的加鎖邏輯
    @ReservedStackAccess
    final boolean tryLock() {
        Thread current = Thread.currentThread();
        //獲取State屬性值,這是在AQS裏面定義的值,用於標記是否可以加鎖,0代表沒有人在用鎖,1代表有人在佔用,大於1說明這個鎖被這個人加了多次【即重入鎖概念】
        int c = getState();
        if (c == 0) {
            //CAS保證只有一個人能成功
            if (compareAndSetState(0, 1)) {
                //設置持有鎖的線程
                setExclusiveOwnerThread(current);
                return true;
            }
        } else if (getExclusiveOwnerThread() == current) { //走到這裡說明有人持有了鎖,但是可以判斷持有的人是不是自己【可重入】
            if (++c < 0) // overflow
                throw new Error("Maximum lock count exceeded");
            //因為每一次重入都會導致State的值+1,所以解鎖的時候對應要減1
            setState(c);
            return true;
        }
        return false;
    }

    //為子類留下的加鎖邏輯的抽象方法
    abstract boolean initialTryLock();

    //核心加鎖邏輯裏面便是使用抽象方法進行加鎖
    @ReservedStackAccess
    final void lock() {
        if (!initialTryLock())
            acquire(1);
    }

    @ReservedStackAccess
    final void lockInterruptibly() throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (!initialTryLock())
            acquireInterruptibly(1);
    }

    @ReservedStackAccess
    final boolean tryLockNanos(long nanos) throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        return initialTryLock() || tryAcquireNanos(1, nanos);
    }

    //嘗試釋放鎖
    @ReservedStackAccess
    protected final boolean tryRelease(int releases) {
        int c = getState() - releases;
        if (getExclusiveOwnerThread() != Thread.currentThread())
            throw new IllegalMonitorStateException();
        boolean free = (c == 0);
        if (free)
            setExclusiveOwnerThread(null);
        setState(c);
        return free;
    }

    protected final boolean isHeldExclusively() {
        // While we must in general read state before owner,
        // we don't need to do so to check if current thread is owner
        return getExclusiveOwnerThread() == Thread.currentThread();
    }

    final ConditionObject newCondition() {
        return new ConditionObject();
    }

    // Methods relayed from outer class

    final Thread getOwner() {
        return getState() == 0 ? null : getExclusiveOwnerThread();
    }

    final int getHoldCount() {
        return isHeldExclusively() ? getState() : 0;
    }

    final boolean isLocked() {
        return getState() != 0;
    }

    /**
     * Reconstitutes the instance from a stream (that is, deserializes it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        setState(0); // reset to unlocked state
    }
}

 

【3】實現抽象的 Sync類 的公平鎖 FairSync類部分

static final class FairSync extends Sync {
    //嘗試鎖定方法
    final boolean initialTryLock() {
        Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {
            //看得出來首先隊列要為空,其次才是CAS加鎖成功,才算能夠持有鎖 
            //也就是說隊列不為空,連CAS加鎖的資格都沒有,所以十分公平
            if (!hasQueuedThreads() && compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        } else if (getExclusiveOwnerThread() == current) {
            if (++c < 0) // overflow
                throw new Error("Maximum lock count exceeded");
            setState(c);
            return true;
        }
        return false;
    }

    //嘗試獲取方法
    protected final boolean tryAcquire(int acquires) {
        if (getState() == 0 && !hasQueuedPredecessors() &&
            compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }
        return false;
    }
}

//AbstractQueuedSynchronizer類#hasQueuedThreads方法
//判斷隊列是否為空【由於AQS裏面採用的是鏈表實現隊列效果,所以是判斷節點情況】
public final boolean hasQueuedThreads() {
    for (Node p = tail, h = head; p != h && p != null; p = p.prev)
        if (p.status >= 0)
            return true;
    return false;
}

 

【4】實現抽象的 Sync類 的非公平鎖 NonfairSync類部分

//與公平的同步器進行比較的話,會發現,他們本質沒什麼區別,因為大多數走的都是抽象方法的邏輯和AQS的方法
//最大的區別在於加鎖的方式不同,公平方式,隊列沒人才去加鎖;非公平方式,不管隊列有沒有人,都是直接去加鎖,加到了就持有
static final class NonfairSync extends Sync {
    //嘗試鎖定方法
    final boolean initialTryLock() {
        Thread current = Thread.currentThread();
        //直接嘗試CAS獲取加鎖權利
        if (compareAndSetState(0, 1)) { // first attempt is unguarded
            setExclusiveOwnerThread(current);
            return true;
        } else if (getExclusiveOwnerThread() == current) {
            int c = getState() + 1;
            if (c < 0) // overflow
                throw new Error("Maximum lock count exceeded");
            setState(c);
            return true;
        } else
            return false;
    }

    //嘗試獲取方法
    protected final boolean tryAcquire(int acquires) {
        //判斷是否有人持有鎖,沒有則去加鎖
        if (getState() == 0 && compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }
        return false;
    }
}