JAVA鎖機制,java鎖
多線程和並發性並不是Java的什麼新內容,Java封裝了與線程相關的類庫,核心類庫包含一個 Thread 類,可以用它來構建、啟動和操縱線程。當然Java官方更推薦的是通過實現Runnable方法實現多線程,因為他更容易使用,可讀性更強,而且可以複用線程池帶來更高的效能。
Java 語言套件括了跨線程傳達並發性約束的構造—— synchronized 和 volatile 。在簡化與平台無關的並發類的開發的同時,它決沒有使並發類的編寫工作變得更繁瑣,只是使它變得更容易了。
多線程編程必然涉及到多線程線程同步問題。java提供了多種處理線程同步問題的方法。
1、synchronized關鍵字
synchronized關鍵字是最常用的一種方法,確實效能、效果最差的方法,但是其可讀性很強,任然被廣泛使用著。
Java中的每一個對象都可以作為鎖。
對於同步方法,鎖是當前執行個體對象。
對於靜態同步方法,鎖是當前對象的Class對象。
對於同步方法塊,鎖是synchonized括弧裡配置的對象。
JVM規範規定JVM基於進入和退出Monitor對象來實現方法同步和代碼塊同步,但兩者的實現細節不一樣。代碼塊同步是使用monitorenter和monitorexit指令實現,而方法同步是使用另外一種方式實現的,細節在JVM規範裡並沒有詳細說明,但是方法的同步同樣可以使用這兩個指令來實現。monitorenter指令是在編譯後插入到同步代碼塊的開始位置,而monitorexit是插入到方法結束處和異常處, JVM要保證每個monitorenter必須有對應的monitorexit與之配對。任何對象都有一個 monitor 與之關聯,當且一個monitor 被持有後,它將處於鎖定狀態。線程執行到 monitorenter 指令時,將會嘗試擷取對象所對應的 monitor 的所有權,即嘗試獲得對象的鎖。
比較常用的是修飾方法,使一個方法可以互斥調用:
/** * Created by jpbirdy on15-1-22. */ package jpbirdy.thread.lock; import java.util.concurrent.locks.ReentrantLock; /** * @author jpbirdy * @project JavaAlgorithms * @class LockTest * @date 15-1-22 13:35 * @desc */public class SynchronizedLockTest{ private int total = 0; //修飾方法的線程同步關鍵字,提供方法層級的鎖 public synchronized voidadd() throws InterruptedException { total ++ ; Thread.sleep(1000); } public int get(){returntotal;} public static class InnerRunnable implements Runnable { privateSynchronizedLockTest synchronizedLockTest; private int threadId; publicInnerRunnable(int threadId , SynchronizedLockTest synchronizedLockTest) { this.synchronizedLockTest = synchronizedLockTest; this.threadId =threadId; } public InnerRunnablesetSynchronizedLockTest(SynchronizedLockTest synchronizedLockTest) { this.synchronizedLockTest = synchronizedLockTest; return this; } @Override public void run() { try { System.out.println(synchronizedLockTest.get()); synchronizedLockTest.add(); } catch(InterruptedException e) { e.printStackTrace(); } System.out.println("thread " + threadId + "addover"); } } public static voidmain(String[] args) throws Exception { SynchronizedLockTestsynchronizedLockTest = new SynchronizedLockTest(); for(int i=0 ; i<10; i++) { new Thread(newInnerRunnable(i, synchronizedLockTest)).start(); Thread.sleep(1); } }}
運行顯示
0111111111thread 0add overthread 9add overthread 8add overthread 7add overthread 6add overthread 5add overthread 4add overthread 3add overthread 2add overthread 1add over
get並沒有加鎖,但set方法加了鎖,所以每個thread都會等待每個add方法執行sleep方法結束後才能重新進入。
對於方法中存在多個區塊,但僅想對某一個部分作為臨界區參與競爭,其他部分是不會有線程同步問題的,則可以用sychronized塊實現:
/** * Created by jpbirdy on 15-1-22. */package jpbirdy.thread.lock;import java.util.concurrent.locks.ReentrantLock;/** * @author jpbirdy * @project JavaAlgorithms * @class LockTest * @date 15-1-22 13:35 * @desc */public class SynchronizedLockTest{ private ReentrantLock lock = new ReentrantLock(); private int total = 0; public int get(){return total;} //代碼塊鎖 public void add2() throws InterruptedException { System.out.println("out of synchronized"); synchronized (this) { total ++ ; Thread.sleep(1000); } } public static class InnerRunnable implements Runnable { private SynchronizedLockTest synchronizedLockTest; private int threadId; public InnerRunnable(int threadId , SynchronizedLockTest synchronizedLockTest) { this.synchronizedLockTest = synchronizedLockTest; this.threadId = threadId; } public InnerRunnable setSynchronizedLockTest(SynchronizedLockTest synchronizedLockTest) { this.synchronizedLockTest = synchronizedLockTest; return this; } @Override public void run() { try {// System.out.println(synchronizedLockTest.get()); synchronizedLockTest.add2(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread " + threadId + "add over"); } } public static void main(String[] args) throws Exception { SynchronizedLockTest synchronizedLockTest = new SynchronizedLockTest(); for(int i=0 ; i<10 ; i++) { new Thread(new InnerRunnable(i, synchronizedLockTest)).start(); Thread.sleep(1); } }}
結果為:
out of synchronizedout of synchronizedout of synchronizedout of synchronizedout of synchronizedout of synchronizedout of synchronizedout of synchronizedout of synchronizedout of synchronizedthread 0add overthread 9add overthread 8add overthread 7add overthread 6add overthread 5add overthread 4add overthread 3add overthread 2add overthread 1add over
僅有add和sleep處於線程同步塊中。
當然理論上sychronized也可以修飾一個類(對象名、類名.class或this表示自己),進行對類整個類的非同步呼叫。這樣可以實現當某個修改操作進行時,擷取操作可以進行等待避免讀到髒資料(DBMS?在JDBC中如果要實現JAVA層的讀寫非同步,可以對Connection對象加鎖,在Hibernate中則對應對Session對象加鎖)
/** * Created by jpbirdy on15-1-22. */ package jpbirdy.thread.lock; /** * @author jialou.jp * @project JavaAlgorithms * @class LockTest * @date 15-1-22 13:35 * @desc */public class ObjectLockTest{ private int total = 0; //修飾對象的線程同步關鍵字,提供方法層級的鎖 public void add() throwsInterruptedException { System.out.println("in add" + Thread.currentThread().getId()); synchronized (this) { System.out.println("in add" + Thread.currentThread().getId() +"get the clock"); total ++ ; Thread.sleep(1000); System.out.println("in add" + Thread.currentThread().getId() +"release the clock"); } } public int get() throwsInterruptedException { System.out.println("in get" +Thread.currentThread().getId()); int total = 0; synchronized (this) { System.out.println("in get" + Thread.currentThread().getId() +"get the clock");// return total; total = this.total; Thread.sleep(1000); System.out.println("in get" + Thread.currentThread().getId() +"release th clock"); } return total; } public static class InnerRunnableimplements Runnable { private ObjectLockTestsynchronizedLockTest; private int threadId; publicInnerRunnable(int threadId , ObjectLockTest synchronizedLockTest) { this.synchronizedLockTest = synchronizedLockTest; this.threadId =threadId; } public InnerRunnablesetSynchronizedLockTest(ObjectLockTest synchronizedLockTest) { this.synchronizedLockTest = synchronizedLockTest; return this; } @Override public void run() { try { System.out.println(synchronizedLockTest.get()); synchronizedLockTest.add(); } catch(InterruptedException e) { e.printStackTrace(); } System.out.println("thread " + threadId + "addover"); } } public static voidmain(String[] args) throws Exception { ObjectLockTestsynchronizedLockTest = new ObjectLockTest(); for(int i=0 ; i<10; i++) { new Thread(newInnerRunnable(i, synchronizedLockTest)).start(); Thread.sleep(1); } }}
結果為:
in get11in get11get the clockin get12in get13in get14in get15in get16in get17in get18in get19in get20in get11release th clock0in get20get the clockin add11in get20release th clock0in get19get the clockin add20in get19release th clock0in add19in get18get the clockin get18release th clock0in add18in get17get the clockin get17release th clock0in add17in get16get the clockin get16release th clock0in add16in get15get the clockin get15release th clock0in add15in get14get the clockin get14release th clock0in add14in get13get the clockin get13release th clock0in add13in get12get the clockin get12release th clock0in add12in add13get the clockin add13release the clockthread 2add overin add14get the clockin add14release the clockthread 3add overin add15get the clockin add15release the clockthread 4add overin add16get the clockin add16release the clockthread 5add overin add17get the clockin add17release the clockthread 6add overin add18get the clockin add18release the clockthread 7add overin add19get the clockin add19release the clockthread 8add overin add20get the clockin add20release the clockthread 9add overin add11get the clockin add11release the clockthread 0add overin add12get the clockin add12release the clockthread 1add over
線程中,get和add會交替獲得(實際上存在順序,這與資源競爭調度有關)鎖,並執行。
值得一提的是,sychronized是一個JVM層級的操作,所以不論同步塊中的代碼執行結果如何,代碼塊執行完成之後必然會釋放對於的鎖,讓其他線程獲得執行權力。
2、ReentrantLock鎖
在JDK1.5之後,出現了一種代碼層級的鎖(java.util.concurrent.lock),這種方式類似於作業系統的metex操作。在對象中建立一個ReentrantLock對象,在需要進行資源競爭時,通過lock.lock()方法可以實現線程同步。
一個類中可以有多個ReentrantLock對象,以標識多個零界資源,實現多個資源多線程競爭操作。
/** *Created by jpbirdy on 15-1-22. */ package jpbirdy.thread.lock; importjava.util.concurrent.locks.ReentrantLock; /** *@author jialou.jp *@project JavaAlgorithms *@class ReentrantLockTest *@date 15-1-22 14:38 *@desc */public class ReentrantLockTest{ private ReentrantLock lock = new ReentrantLock(); private int total = 0; public void add() throws InterruptedException { lock.lock(); total ++; Thread.sleep(1000); lock.unlock(); } public static class InnerRunnable implements Runnable { private ReentrantLockTest reentrantLockTest; public InnerRunnable(ReentrantLockTest reentrantLockTest) { this.reentrantLockTest = reentrantLockTest; } @Override public void run() { try { reentrantLockTest.add(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("add over"); } } public static void main(String[] args) throws Exception { ReentrantLockTest reentrantLockTest = new ReentrantLockTest(); for(int i=0 ; i<10 ; i++) { new Thread(new InnerRunnable(reentrantLockTest)).start(); Thread.sleep(1); } }}
結果如下:
add overadd overadd overadd overadd overadd overadd overadd overadd overadd over
著名的ConcurrentHashMap就是通過ReentrantLock實現線程同步的。
3、區別
從靈活性上來說,ReentrantLock的靈活性必然更高。因為該鎖是代碼層級實現的,可以隨時釋放,也可以再擷取。
例如在程式中,當代碼執行到某個步驟(比如某個初始化完成之後),後面的步驟可以不用著急做,就可以暫時將鎖釋放,同時調用yield方法讓線程重新進行調度。如果系統任務現在又更需要獲得CPU資源的線程,則他在此時也可以獲得鎖進行操作,否則資源的調度就沒有意義。
而在sychronized中,一旦線程獲得運行權(即鎖),將必須消費直到塊/方法結束,也就是說在此時,無論作業系統做如何調度,其他線程都無法獲得鎖而去得方法的運行權。
但sychronized的好處就是可讀性強。而且其實在JVM上實現的,可以理解為使一個輕量級的鎖控制模式。在任務不是非常複雜的情況下應該是有限使用sychronized方法實現線程同步。同時上文也提到,sychronized是JVM層級的一種機制,所以無論sychronized塊中執行的結果如何,都將釋放該鎖。而ReentrantLock就不同,由於其實代碼層級的鎖,一旦代碼中拋出異常,這將導致整個代碼塊block掉,unlock方法就一定不會執行了,所以在使用ReentrantLock的時候,習慣上會將lock以下的內容用try-catch-finally包住,並將unlock方法放到finally中。否則容易引起死結。
另外需要注意的就是效率。這裡引用一段:
比較ReentrantLock 和 synchronized 的延展性
Tim Peierls 用一個簡單的線性全等偽隨機數產生器(PRNG)構建了一個簡單的評測,用它來測量 synchronized 和 Lock 之間相對的延展性。這個樣本很好,因為每次調用 nextRandom() 時,PRNG 都確實在做一些工作,所以這個基準程式實際上是在測量一個合理的、真實的 synchronized 和 Lock 應用程式,而不是測試純粹紙上談兵或者什麼也不做的代碼(就像許多所謂的基準程式一樣。)
在這個基準程式中,有一個PseudoRandom 的介面,它只有一個方法 nextRandom(int bound) 。該介面與 java.util.Random類的功能非常類似。因為在產生下一個隨機數時,PRNG 用最新產生的數字作為輸入,而且把最後產生的數字作為一個執行個體變數來維護,其重點在於讓更新這個狀態的程式碼片段不被其他線程搶佔,所以我要用某種形式的鎖定來確保這一點。( java.util.Random 類也可以做到這點。)我們為 PseudoRandom 構建了兩個實現;一個使用 syncronized,另一個使用 java.util.concurrent.ReentrantLock 。驅動程式產生了大量線程,每個線程都瘋狂地爭奪時間片,然後計算不同版本每秒能執行多少輪。圖 1 和圖 2 總結了不同線程數量的結果。這個評測並不完美,而且只在兩個系統上運行了(一個是雙 Xeon 運行超執行緒 Linux,另一個是單一處理器 Windows 系統),但是,應當足以表現 synchronized 與 ReentrantLock 相比所具有的伸縮性優勢了。
圖 1 和圖 2 中的圖表以每秒調用數為單位顯示了吞吐率,把不同的實現調整到 1 線程 synchronized 的情況。每個實現都相對迅速地集中在某個穩定點的吞吐率上,該狀態通常要求處理器得到充分利用,把大多數的處理器時間都花在處理實際工作(電腦隨機數)上,只有小部分時間花在了線程調度開支上。您會注意到,synchronized 版本在處理任何類型的爭用時,表現都相當差,而 Lock 版本在調度的開支上花的時間相當少,從而為更高的吞吐率留下空間,實現了更有效 CPU 利用。
綜合分析,ReentrantLock擁有更高的靈活性,在多個資源競爭同一個鎖時,其效能將高於sychronized塊。實驗也證明,線上程增大的情況下sychronized塊的執行效率會急劇下降。
各方面來看,ReentrantLock是優於sychronized塊的,但在資源競爭不激烈的情況下,效能並沒有出現瓶頸時還是應當優先使用sychronized塊,增加代碼的可讀性。但當我們需要一個可自由定製,可以投票獲得鎖或更加靈活的鎖控制時,可以毫不猶豫選擇ReentrantLock進行控制。
5次真言。Do It Best, Then fastest!