java 線程公平鎖與非公平鎖詳解及實例代碼
java 線程公平鎖與非公平鎖詳解
在ReentrantLock中很明顯可以看到其中同步包括兩種,分別是公平的FairSync和非公平的NonfairSync。公平鎖的作用就是嚴格按照線程啟動的順序來執(zhí)行的,不允許其他線程插隊執(zhí)行的;而非公平鎖是允許插隊的。
默認情況下ReentrantLock是通過非公平鎖來進行同步的,包括synchronized關鍵字都是如此,因為這樣性能會更好。因為從線程進入了RUNNABLE狀態(tài),可以執(zhí)行開始,到實際線程執(zhí)行是要比較久的時間的。而且,在一個鎖釋放之后,其他的線程會需要重新來獲取鎖。其中經歷了持有鎖的線程釋放鎖,其他線程從掛起恢復到RUNNABLE狀態(tài),其他線程請求鎖,獲得鎖,線程執(zhí)行,這一系列步驟。如果這個時候,存在一個線程直接請求鎖,可能就避開掛起到恢復RUNNABLE狀態(tài)的這段消耗,所以性能更優(yōu)化。
/** * Creates an instance of {@code ReentrantLock}. * This is equivalent to using {@code ReentrantLock(false)}. */ public ReentrantLock() { sync = new NonfairSync(); }
默認狀態(tài),使用的ReentrantLock()就是非公平鎖。再參考如下代碼,我們知道ReentrantLock的獲取鎖的操作是通過裝飾模式代理給sync的。
/** * Acquires the lock. * * <p>Acquires the lock if it is not held by another thread and returns * immediately, setting the lock hold count to one. * * <p>If the current thread already holds the lock then the hold * count is incremented by one and the method returns immediately. * * <p>If the lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until the lock has been acquired, * at which time the lock hold count is set to one. */ public void lock() { sync.lock(); }
下面參考一下FairSync和NonfairSync對lock方法的實現:
/** * Sync object for non-fair locks */ static final class NonfairSync extends Sync { /** * Performs lock. Try immediate barge, backing up to normal * acquire on failure. */ final void lock() { if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); } } /** * Sync object for fair locks */ static final class FairSync extends Sync { final void lock() { acquire(1); } }
當使用非公平鎖的時候,會立刻嘗試配置狀態(tài),成功了就會插隊執(zhí)行,失敗了就會和公平鎖的機制一樣,調用acquire()方法,以排他的方式來獲取鎖,成功了立刻返回,否則將線程加入隊列,知道成功調用為止。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
微服務Spring Boot 整合 Redis 實現UV 數據統(tǒng)計的詳
這篇文章主要介紹了微服務Spring Boot 整合 Redis 實現 UV 數據統(tǒng)計,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-01-01Spring Security 實現多種登錄方式(常規(guī)方式外的郵件、手機驗證碼登錄)
本文主要介紹了Spring Security 實現多種登錄方式(常規(guī)方式外的郵件、手機驗證碼登錄),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01SpringBoot @ConfigurationProperties注解的簡單使用
即便現在簡化了配置,但是一個獨立的配置文件總是易于理解而且使人安心的。Spring在構建完項目后,會默認在resources文件夾下創(chuàng)建一個application.properties文件,application.yml也是一樣的效果。@ConfigurationProperties可以獲取配置文件中的數據,將其注入類。2021-05-05