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; } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/519151.html
標籤:其他
