Monitor
類。 在本文中,我將繼續介紹Guava并發實用程序,并討論ListenableFuture
接口。 ListenableFuture
通過添加接受完成偵聽器的方法,從java.util.concurrent包擴展了Future
接口。 可聽的未來
ListenableFuture
行為與java.util.concurrent.Future
完全相同,但是具有方法addCallback(Runnable, ExecutorService)
在給定的executor
中執行回調。 這是一個例子:
ListenableFuture futureTask = executorService.submit(callableTask)futureTask.addListener(new Runnable() {@Overridepublic void run() {..work after futureTask completed}}, executorService);
如果您在添加回調時提交的任務已完成,它將立即運行。 使用addCallback
方法有一個缺點,即Runnable
無法訪問future
產生的結果。 要訪問Future
的結果,您需要使用FutureCallback
。
FutureCallback
FutureCallback
接受從Future
產生的結果,并指定onSuccess
和onFailure
方法。 這是一個例子:
class FutureCallbackImpl implements FutureCallback<String> {@Overridepublic void onSuccess(String result){.. work with result}@Overridepublic void onFailure(Throwable t) {... handle exception}}
通過使用Futures類中的addCallback
方法來附加FutureCallback
:
Futures.addCallback(futureTask, futureCallbackImpl);
此時,您可能會問,當ExecutorService
僅返回Futures
時,如何獲取ListenableFuture
實例? 答案是使用ListenableExecutionService
。
ListenableExecutionService
要使用ListenableExecutionService
只需使用對MoreExecutors.listeningDecorator(ExecutorService)
的調用來裝飾ExecutorService
實例,例如:
ExecutorsService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
結論
借助添加回調(無論是Runnable
還是處理成功和失敗條件的FutureCallback
功能, ListenableFuture
可能會成為您的武器庫的寶貴補充。 我創建了一個單元測試使用證明ListenableFuture
可以作為一個依據 。 在我的下一個職位,我要覆蓋Futures
類,它包含與工作靜態方法futures
。
資源資源
- 番石榴項目首頁
- ListenableFuture API
- 樣例代碼
參考: Google Guava并發–我們的JCG合作伙伴 Bill Bejeck的《可編碼的隨機想法》博客中的ListenableFuture。
翻譯自: https://www.javacodegeeks.com/2012/11/google-guava-concurrency-listenablefuture.html