本文為后續(xù)介紹AbstractQueuedSynchronizer.ConditionObject做一下鋪墊。
Lock&Condition
Lock用于控制多線程對(duì)同一狀態(tài)的順序訪問(wèn),保證該狀態(tài)的連續(xù)性耀石。
Condition用于控制多線程之間的旋炒、基于該狀態(tài)的條件等待朦前。
PS:這里的“同一狀態(tài)”指的就是“需要爭(zhēng)用的共享資源”祈餐。
舉例說(shuō)明(出自java Condition的注釋?zhuān)?br> 這是一個(gè)簡(jiǎn)單的生產(chǎn)者消費(fèi)者模型,生產(chǎn)者往buffer里put悯辙,消費(fèi)者從buffer里take。
- 同一狀態(tài)的順序訪問(wèn)
有三個(gè)狀態(tài)需要順序訪問(wèn):buffer的大小count,生產(chǎn)者用于put的游標(biāo)putptr笑撞,消費(fèi)者用于take的游標(biāo)takeptr岛啸。 - 基于該狀態(tài)的條件等待
當(dāng)count = 0時(shí),消費(fèi)者的take需要等待茴肥;當(dāng)count = buffer.size(buffer滿了)坚踩,生產(chǎn)者需要等待。
If a take is attempted on an empty buffer, then the thread will block until an item becomes available; if a put is attempted on a full buffer, then the thread will block until a space becomes available.
代碼如下:
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}
這里瓤狐,lock用于保證count, takeptr, putptr這三個(gè)狀態(tài)的順序訪問(wèn)瞬铸,notFull和notEmpty用來(lái)控制基于count的條件等待。
lock的作用很好理解础锐。大家都要修改同一個(gè)count嗓节,需要一個(gè)一個(gè)的來(lái),而在根據(jù)count進(jìn)行條件判斷時(shí)皆警,自然也是要先拿到這個(gè)lock拦宣,才能保證這個(gè)count的準(zhǔn)確性。所以信姓,不論是修改count鸵隧,還是基于count進(jìn)行判斷,均是在lock之后執(zhí)行意推。
不過(guò)豆瘫,既然lock已經(jīng)保證了一次只有一個(gè)線程能夠訪問(wèn)count,那為何不能完全基于lock來(lái)實(shí)現(xiàn)一個(gè)生產(chǎn)者和消費(fèi)者模型呢菊值,要Condition作甚外驱?我想了想,寫(xiě)了一個(gè)完全基于lock的put()腻窒。
public void put(Object x) throws InterruptedException {
while (true) {
lock.lock();
try {
if (count < items.length) {
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
break;
}
} finally {
lock.unlock();
}
}
}
這個(gè)put是基于循環(huán)來(lái)做的昵宇,獲取到鎖后,如果條件不滿足儿子,就釋放鎖趟薄,然后再繼續(xù)獲取鎖。我覺(jué)得典徊,這個(gè)版本在邏輯上應(yīng)該是沒(méi)問(wèn)題的,是能夠保證生產(chǎn)者消費(fèi)者模型的正確執(zhí)行的恩够。不過(guò)卒落,問(wèn)題在于,不停的獲取鎖蜂桶、釋放鎖儡毕,效率太低了,甚至可能出現(xiàn)某個(gè)生產(chǎn)者線程總是能夠不停的成功獲取鎖,直接阻塞住其他的生產(chǎn)者或消費(fèi)者腰湾,導(dǎo)致整個(gè)模型在一段時(shí)間內(nèi)陷入停滯狀態(tài)雷恃。
自然的解決方法就是,條件不滿足時(shí)费坊,掛起線程倒槐,在條件滿足時(shí),再喚醒附井。
掛起再喚醒讨越,Lock干的也是類(lèi)似的事情。不過(guò)永毅,在生產(chǎn)者消費(fèi)者模型中把跨,當(dāng)條件不滿足時(shí),應(yīng)當(dāng)立即掛起線程沼死。而lock()并不是一個(gè)直接掛起線程的方法着逐,獲取鎖失敗時(shí),才會(huì)掛起線程意蛀。
總之耸别,多線程在對(duì)同一狀態(tài)進(jìn)行修改時(shí),需要用Lock保證其一致性浸间,而在線程需要基于該狀態(tài)進(jìn)行條件等待時(shí)太雨,為了保證高效性,得有一個(gè)方法來(lái)控制線程在該條件上的掛起和喚醒魁蒜。于是囊扳,Condition就應(yīng)運(yùn)而生了。因?yàn)镃ondition涉及到的狀態(tài)兜看,應(yīng)是某個(gè)需要被Lock的狀態(tài)锥咸,所以至少在有Lock的場(chǎng)景下,才會(huì)有Condition细移,這也是為什么Lock和Condition總是捉對(duì)出現(xiàn)搏予。
Lock和Condition的實(shí)現(xiàn)簡(jiǎn)介
Lock和Condition的實(shí)現(xiàn)都是基于隊(duì)列的。一般將Lock維護(hù)的隊(duì)列稱(chēng)作syn queue弧轧,將Condition維護(hù)的隊(duì)列稱(chēng)作condition queue雪侥。
這兩個(gè)隊(duì)列的協(xié)作如下:
- syn queue按照順序維護(hù)需要訪問(wèn)共享資源的多個(gè)線程,每次只有隊(duì)列最前端的線程才能獲取資源精绎;
- 當(dāng)一個(gè)線程獲取到資源后速缨,卻發(fā)現(xiàn)依賴(lài)資源的條件不成立時(shí),就會(huì)被掛起并移到對(duì)應(yīng)的condition queue中去代乃;
- 當(dāng)依賴(lài)資源的條件成立后旬牲,該線程就會(huì)被喚醒,并從condition queue再移至syn queue中。
上面一直將Lock和Condition當(dāng)做兩個(gè)概念來(lái)說(shuō)原茅,其實(shí)吭历,它們?cè)趈ava中僅僅是兩個(gè)接口,實(shí)現(xiàn)了這兩個(gè)接口的類(lèi)是AbstractQueuedSynchronizer擂橘,而一些具體的Lock則是基于AbstractQueuedSynchronizer實(shí)現(xiàn)的晌区。
這里以ReentrantLock為例,實(shí)現(xiàn)的結(jié)構(gòu)類(lèi)似下面這樣子:
class AbstractQueuedSynchronizer
//syn queue
class ConditionObject implements Condition
...
class ReentrantLock implements Lock
class Sync extends AbstractQueuedSynchronizer
這里AbstractQueuedSynchronizer實(shí)現(xiàn)的syn queue僅用注釋的形式標(biāo)識(shí)了下贝室,詳細(xì)說(shuō)明可參見(jiàn)Java AbstractQueuedSynchronizer源碼閱讀1-基于隊(duì)列的同步器框架契讲,condition queue則是在AbstractQueuedSynchronizer的內(nèi)部類(lèi)ConditionObject中實(shí)現(xiàn)的。
Lock的一個(gè)具體實(shí)現(xiàn)ReentrantLock使用了AbstractQueuedSynchronizer來(lái)實(shí)現(xiàn)鎖的機(jī)制滑频。
從這里可以看到捡偏,ConditionObject是作為AbstractQueuedSynchronizer的內(nèi)部類(lèi)來(lái)實(shí)現(xiàn)的,這表示峡迷,得首先有一個(gè)AbstractQueuedSynchronizer的實(shí)例银伟,才能新建一個(gè)ConditionObject。這更進(jìn)一步說(shuō)明了绘搞,Condition存在的前提是必須有Lock彤避。
介紹完Lock&Condition之后,本文再提一下另外兩個(gè)有關(guān)的概念synchronized&Object monitor methods夯辖。
synchronized&Object monitor methods
synchronized:Java關(guān)鍵字琉预,可用來(lái)給對(duì)象、方法或代碼塊加鎖蒿褂。被它鎖定的方法或代碼塊圆米,同一時(shí)刻最多只能有一個(gè)線程執(zhí)行這段代碼。
Object monitor methods:三個(gè)方法:wait()啄栓、notify()娄帖、notifyAll(),以下為三個(gè)方法在java中的部分注釋
wait()
Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor.
notify()
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened.
notifyAll()
Wakes up all threads that are waiting on this object's monitor.
可以看到昙楚,synchronized和Lock在功能上類(lèi)似近速,都可以保證多線程對(duì)一段代碼的順序執(zhí)行;Object monitor methods則和Condition類(lèi)似堪旧,前者在某個(gè)object上進(jìn)行等待和喚醒削葱,而后者在某個(gè)條件上進(jìn)行等待和喚醒。
java其實(shí)是先有的synchronized&Object monitor methods淳梦,后有的Lock&Condition佩耳。
引用一下java的注釋對(duì)二者的關(guān)系進(jìn)行下說(shuō)明:
Lock
Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.
Condition
Condition factors out the Object monitor methods (wait, notify and notifyAll) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations.Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.
總之,Lock&Condition比synchronized&Object monitor methods支持更多的功能谭跨,但是同時(shí)也承擔(dān)更多風(fēng)險(xiǎn)。下面簡(jiǎn)單說(shuō)兩個(gè)例子。
Lock&Condition支持更多的功能
Lock&Condition支持線程等待的超時(shí)和中斷螃宙,這可以避免線程因?yàn)槟承┰颍ㄈ鏘O等待或是調(diào)用了sleep()方法)長(zhǎng)期占有鎖而不釋放蛮瞄。
Lock&Condition可支持讀者寫(xiě)者模型中,多個(gè)讀者可同時(shí)獲取鎖的情況谆扎。
Lock&Condition承擔(dān)更多的風(fēng)險(xiǎn)
synchronized不需要用戶(hù)手動(dòng)釋放鎖挂捅,由JVM自動(dòng)釋放;Lock則必須要用戶(hù)手動(dòng)釋放鎖堂湖,如果處理不慎闲先,就有可能導(dǎo)致死鎖。