Google Guava項目是每個Java開發人員都應該熟悉的庫的集合。 Guava庫涵蓋I / O,集合,字符串操作和并發性。 在這篇文章中,我將介紹Monitor類。 Monitor是一種同步構造,可以在使用ReentrantLock的任何地方使用。 在任何時候,只有一個線程可以占用一個監視器。 Monitor類具有進入和離開操作,這些操作在語義上與ReentrantLock中的鎖定和解鎖操作相同。 此外,監視器支持在布爾條件下等待。
比較Monitor和ReentrantLock
對于初學者,將Monitor和ReentrantLock進行并排比較會很有幫助。
public class ReentrantLockSample {private List<String> list = new ArrayList<String>();private static final int MAX_SIZE = 10;private ReentrantLock rLock = new ReentrantLock();private Condition listAtCapacity = rLock.newCondition();public void addToList(String item) throws InterruptedException {rLock.lock();try {while (list.size() == MAX_SIZE) {listAtCapacity.await();}list.add(item);} finally {rLock.unlock();}}
}
public class MonitorSample {private List<String> list = new ArrayList<String>();private static final int MAX_SIZE = 10;private Monitor monitor = new Monitor();private Monitor.Guard listBelowCapacity = new Monitor.Guard(monitor) {@Overridepublic boolean isSatisfied() {return (list.size() < MAX_SIZE);}};public void addToList(String item) throws InterruptedException {monitor.enterWhen(listBelowCapacity);try {list.add(item);} finally {monitor.leave();}}
}
從示例中可以看到,兩者實際上具有相同數量的代碼行。 與ReentrantLock Condition
相比, Monitor
會在Guard
對象周圍增加一些復雜性。 但是, Monitor
addToList
方法的清晰度遠遠不能彌補。 這可能只是我的個人喜好,但我一直發現
while(something==true){condition.await()
}
有點尷尬。
使用指南
應當注意,返回void
enter
方法應始終采用以下形式:
monitor.enter()
try{...work..
}finally{monitor.leave();
}
并enter
返回boolean
方法應類似于:
if(monitor.enterIf(guard)){try{...work..}finally{monitor.leave();}
}else{.. monitor not available..
}
布爾條件
Monitor類上的enter
方法太多,無法有效地完成一篇文章,所以我將挑選我的前三名,然后按照從最小阻塞到最大阻塞的順序進行介紹。
- tryEnterIf –線程將不等待進入監視器,僅在保護條件返回true時才進入。
- enterIf –線程將等待進入監視器,但前提是保護條件返回true。 還有enterIf方法簽名,這些簽名允許指定超時以及enterIfInterruptible版本。
- enterWhen –線程將無限期等待監視器和條件返回true,但可以被中斷。 同樣,也有用于指定超時的選項以及enterWhenUniterruptible版本。
結論
我還沒有機會在工作中使用Monitor,但是我可以看到布爾保護條件的粒度有用。 我已經寫了一些基本的示例代碼和一個隨附的單元測試,以演示本文所涵蓋的一些功能。 它們在這里可用。 一如既往地歡迎您提出意見/建議。 在我的下一篇文章中,我將介紹Guava并發中的更多內容。
資源資源
- 番石榴項目首頁
- 監控器API
- 樣例代碼
參考資料: Google Guava –我們的JCG合作伙伴 Bill Bejeck在“ 隨機編碼想法”博客上與Monitor進行了同步 。
翻譯自: https://www.javacodegeeks.com/2012/11/google-guava-synchronization-with-monitor.html