# 5.1-google Guava包的ListenableFuture解析
[原文地址](http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained)? 譯者:**羅立樹** ?校對:**方騰飛**
并發編程是一個難題,但是一個強大而簡單的抽象可以顯著的簡化并發的編寫。出于這樣的考慮,Guava 定義了?[ListenableFuture](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/ListenableFuture.html)接口并繼承了JDK concurrent包下的`Future`?接口。
**我們強烈地建議你在代碼中多使用`ListenableFuture來代替JDK的`?`Future`**, 因為:
* `大多數Futures`?方法中需要它。
* 轉到`ListenableFuture`?編程比較容易。
* Guava提供的通用公共類封裝了公共的操作方方法,不需要提供Future和`ListenableFuture的擴展方法。`
## 接口
傳統JDK中的Future通過異步的方式計算返回結果:在多線程運算中可能或者可能在沒有結束返回結果,Future是運行中的多線程的一個引用句柄,確保在服務執行返回一個Result。
ListenableFuture可以允許你注冊回調方法(callbacks),在運算(多線程執行)完成的時候進行調用, ?或者在運算(多線程執行)完成后立即執行。這樣簡單的改進,使得可以明顯的支持更多的操作,這樣的功能在JDK concurrent中的Future是不支持的。
`ListenableFuture`?中的基礎方法是[`addListener(Runnable, Executor)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…ommon/util/concurrent/ListenableFuture.html#addListener%28java.lang.Runnable, java.util.concurrent.Executor%29), 該方法會在多線程運算完的時候,指定的Runnable參數傳入的對象會被指定的Executor執行。
## 添加回調(Callbacks)
多數用戶喜歡使用?[Futures.addCallback(ListenableFuture<V>, FutureCallback<V>, Executor)](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…utures.html#addCallback%28com.google.common.util.concurrent.ListenableFuture, com.google.common.util.concurrent.FutureCallback, java.util.concurrent.Executor%29)的方式, 或者 另外一個版本[version](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…utures.html#addCallback%28com.google.common.util.concurrent.ListenableFuture, com.google.common.util.concurrent.FutureCallback%29)(譯者注:[addCallback](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/src-html/com/google/common/util/concurrent/Futures.html#line.1106)([ListenableFuture](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/ListenableFuture.html "interface in com.google.common.util.concurrent")<V>?future,[FutureCallback](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/FutureCallback.html "interface in com.google.common.util.concurrent")<? super V>?callback)),默認是采用?`MoreExecutors.sameThreadExecutor()線程池`, 為了簡化使用,Callback采用輕量級的設計. ?[`FutureCallback<V>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/FutureCallback.html)?中實現了兩個方法:
* [`onSuccess(V)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/FutureCallback.html#onSuccess%28V%29),在Future成功的時候執行,根據Future結果來判斷。
* [`onFailure(Throwable)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…e/common/util/concurrent/FutureCallback.html#onFailure%28java.lang.Throwable%29),?在Future失敗的時候執行,根據Future結果來判斷。
## ListenableFuture的創建
對應JDK中的?[`ExecutorService.submit(Callable)`](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html#submit%28java.util.concurrent.Callable%29)?提交多線程異步運算的方式,Guava 提供了[`ListeningExecutorService`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/ListeningExecutorService.html)?接口, 該接口返回?`ListenableFuture`?而相應的?`ExecutorService`?返回普通的?`Future`。將?`ExecutorService`?轉為?`ListeningExecutorService,`可以使用[MoreExecutors.listeningDecorator(ExecutorService)](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…MoreExecutors.html#listeningDecorator%28java.util.concurrent.ExecutorService%29)進行裝飾。
```
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture explosion = service.submit(new Callable() {
public Explosion call() {
return pushBigRedButton();
}
});
Futures.addCallback(explosion, new FutureCallback() {
// we want this handler to run immediately after we push the big red button!
public void onSuccess(Explosion explosion) {
walkAwayFrom(explosion);
}
public void onFailure(Throwable thrown) {
battleArchNemesis(); // escaped the explosion!
}
});
```
另外, 假如你是從?[FutureTask](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/FutureTask.html)轉換而來的, Guava 提供[`ListenableFutureTask.create(Callable<V>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…/concurrent/ListenableFutureTask.html#create%28java.util.concurrent.Callable%29)?和[`ListenableFutureTask.create(Runnable, V)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…common/util/concurrent/ListenableFutureTask.html#create%28java.lang.Runnable, V%29). 和 JDK不同的是,?`ListenableFutureTask`?不能隨意被繼承(譯者注:ListenableFutureTask中的done方法實現了調用listener的操作)。
假如你喜歡抽象的方式來設置future的值,而不是想實現接口中的方法,可以考慮繼承抽象類[`AbstractFuture<V>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/AbstractFuture.html)?或者直接使用?[`SettableFuture`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/SettableFuture.html)?。
假如你必須將其他API提供的Future轉換成?`ListenableFuture`,你沒有別的方法只能采用硬編碼的方式[`JdkFutureAdapters.listenInPoolThread(Future)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/JdkFutureAdapters.html)?來將?`Future`?轉換成?`ListenableFuture`。盡可能地采用修改原生的代碼返回?`ListenableFuture`會更好一些。
## Application
使用`ListenableFuture`?最重要的理由是它可以進行一系列的復雜鏈式的異步操作。
```
ListenableFuture rowKeyFuture = indexService.lookUp(query);
AsyncFunction<RowKey, QueryResult> queryFunction =
new AsyncFunction<RowKey, QueryResult>() {
public ListenableFuture apply(RowKey rowKey) {
return dataService.read(rowKey);
}
};
ListenableFuture queryFuture = Futures.transform(rowKeyFuture, queryFunction, queryExecutor);
```
其他更多的操作可以更加有效的支持而JDK中的Future是沒法支持的.
不同的操作可以在不同的Executors中執行,單獨的`ListenableFuture`?可以有多個操作等待。
當一個操作開始的時候其他的一些操作也會盡快開始執行–“fan-out”–`ListenableFuture`?能夠滿足這樣的場景:促發所有的回調(callbacks)。反之更簡單的工作是,同樣可以滿足“fan-in”場景,促發`ListenableFuture`?獲取(get)計算結果,同時其它的Futures也會盡快執行:可以參考?[the implementation of?`Futures.allAsList`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/src-html/com/google/common/util/concurrent/Futures.html#line.1276)?。(譯者注:fan-in和fan-out是軟件設計的一個術語,可以參考這里: http://baike.baidu.com/view/388892.htm#1 或者看這里的解析 [Design Principles: Fan-In vs Fan-Out](http://it.toolbox.com/blogs/enterprise-solutions/design-principles-fanin-vs-fanout-16088 "Design Principles: Fan-In vs Fan-Out") ,這里fan-out的實現就是封裝的ListenableFuture通過回調,調用其它代碼片段。fan-in的意義是可以調用其它Future)
| 方法 | 描述 | 參考 |
|:--- |:--- |:--- |
| [`transform(ListenableFuture<A>, AsyncFunction<A, B>, Executor)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…/Futures.html#transform%28com.google.common.util.concurrent.ListenableFuture, com.google.common.util.concurrent.AsyncFunction, java.util.concurrent.Executor%29)`*` | `返回一個新的ListenableFuture`?,該`ListenableFuture`?返回的result是由傳入的`AsyncFunction`?參數指派到傳入的?`ListenableFuture中`. | [`transform(ListenableFuture<A>, AsyncFunction<A, B>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…/Futures.html#transform%28com.google.common.util.concurrent.ListenableFuture, com.google.common.util.concurrent.AsyncFunction%29) |
| [`transform(ListenableFuture<A>, Function<A, B>, Executor)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…/Futures.html#transform%28com.google.common.util.concurrent.ListenableFuture, com.google.common.base.Function, java.util.concurrent.Executor%29) | `返回一個新的ListenableFuture`?,該`ListenableFuture`?返回的result是由傳入的`Function`?參數指派到傳入的?`ListenableFuture中`. | [`transform(ListenableFuture<A>, Function<A, B>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…/Futures.html#transform%28com.google.common.util.concurrent.ListenableFuture, com.google.common.base.Function%29) |
| [`allAsList(Iterable<ListenableFuture<V>>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/Futures.html#allAsList%28java.lang.Iterable%29) | `返回一個ListenableFuture`?,該`ListenableFuture`?返回的result是一個List,List中的值是每個ListenableFuture的返回值,假如傳入的其中之一fails或者cancel,這個Future fails 或者canceled | [`allAsList(ListenableFuture<V>...)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…/Futures.html#allAsList%28com.google.common.util.concurrent.ListenableFuture...%29) |
| [`successfulAsList(Iterable<ListenableFuture<V>>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…le/common/util/concurrent/Futures.html#successfulAsList%28java.lang.Iterable%29) | `返回一個ListenableFuture`?,該Future的結果包含所有成功的Future,按照原來的順序,當其中之一Failed或者cancel,則用null替代 | [`successfulAsList(ListenableFuture<V>...)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…s.html#successfulAsList%28com.google.common.util.concurrent.ListenableFuture...%29) |
[`AsyncFunction<A, B>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/AsyncFunction.html)?中提供一個方法`ListenableFuture<B> apply(A input),`它可以被用于異步變換值。
```
List<ListenableFuture> queries;
// The queries go to all different data centers, but we want to wait until they're all done or failed.
ListenableFuture<List> successfulQueries = Futures.successfulAsList(queries);
Futures.addCallback(successfulQueries, callbackOnSuccessfulQueries);
```
## CheckedFuture
Guava也提供了?[`CheckedFuture<V, X extends Exception>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/CheckedFuture.html)?接口。`CheckedFuture`?是一個`ListenableFuture`?,其中包含了多個版本的get 方法,方法聲明拋出檢查異常.這樣使得創建一個在執行邏輯中可以拋出異常的Future更加容易 。將?`ListenableFuture`?轉換成`CheckedFuture`,可以使用?[`Futures.makeChecked(ListenableFuture<V>, Function<Exception, X>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…utures.html#makeChecked%28com.google.common.util.concurrent.ListenableFuture, com.google.common.base.Function%29)。
Guava也提供了?[`CheckedFuture<V, X extends Exception>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/CheckedFuture.html)?接口。`CheckedFuture`?是一個`ListenableFuture`?,其中包含了多個版本的get 方法,方法聲明拋出檢查異常.這樣使得創建一個在執行邏輯中可以拋出異常的Future更加容易 。將?`ListenableFuture`?轉換成`CheckedFuture`,可以使用?[`Futures.makeChecked(ListenableFuture<V>, Function<Exception, X>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…utures.html#makeChecked%28com.google.common.util.concurrent.ListenableFuture, com.google.common.base.Function%29)。
Guava也提供了?[`CheckedFuture<V, X extends Exception>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/CheckedFuture.html)?接口。`CheckedFuture`?是一個`ListenableFuture`?,其中包含了多個版本的get 方法,方法聲明拋出檢查異常.這樣使得創建一個在執行邏輯中可以拋出異常的Future更加容易 。將?`ListenableFuture`?轉換成`CheckedFuture`,可以使用?[`Futures.makeChecked(ListenableFuture<V>, Function<Exception, X>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…utures.html#makeChecked%28com.google.common.util.concurrent.ListenableFuture, com.google.common.base.Function%29)。
Guava也提供了?[`CheckedFuture<V, X extends Exception>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/CheckedFuture.html)?接口。`CheckedFuture`?是一個`ListenableFuture`?,其中包含了多個版本的get 方法,方法聲明拋出檢查異常.這樣使得創建一個在執行邏輯中可以拋出異常的Future更加容易 。將?`ListenableFuture`?轉換成`CheckedFuture`,可以使用?[`Futures.makeChecked(ListenableFuture<V>, Function<Exception, X>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…utures.html#makeChecked%28com.google.common.util.concurrent.ListenableFuture, com.google.common.base.Function%29)。
Guava也提供了?[`CheckedFuture<V, X extends Exception>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/CheckedFuture.html)?接口。`CheckedFuture`?是一個`ListenableFuture`?,其中包含了多個版本的get 方法,方法聲明拋出檢查異常.這樣使得創建一個在執行邏輯中可以拋出異常的Future更加容易 。將?`ListenableFuture`?轉換成`CheckedFuture`,可以使用?[`Futures.makeChecked(ListenableFuture<V>, Function<Exception, X>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…utures.html#makeChecked%28com.google.common.util.concurrent.ListenableFuture, com.google.common.base.Function%29)。
Guava也提供了?[`CheckedFuture<V, X extends Exception>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/CheckedFuture.html)?接口。`CheckedFuture`?是一個`ListenableFuture`?,其中包含了多個版本的get 方法,方法聲明拋出檢查異常.這樣使得創建一個在執行邏輯中可以拋出異常的Future更加容易 。將?`ListenableFuture`?轉換成`CheckedFuture`,可以使用?[`Futures.makeChecked(ListenableFuture<V>, Function<Exception, X>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…utures.html#makeChecked%28com.google.common.util.concurrent.ListenableFuture, com.google.common.base.Function%29)。
Guava也提供了?[`CheckedFuture<V, X extends Exception>`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/CheckedFuture.html)?接口。`CheckedFuture`?是一個`ListenableFuture`?,其中包含了多個版本的get 方法,方法聲明拋出檢查異常.這樣使得創建一個在執行邏輯中可以拋出異常的Future更加容易 。將?`ListenableFuture`?轉換成`CheckedFuture`,可以使用?[`Futures.makeChecked(ListenableFuture<V>, Function<Exception, X>)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/…utures.html#makeChecked%28com.google.common.util.concurrent.ListenableFuture, com.google.common.base.Function%29)。
- Google Guava官方教程(中文版)
- 1-基本工具
- 1.1-使用和避免null
- 1.2-前置條件
- 1.3-常見Object方法
- 1.4-排序: Guava強大的”流暢風格比較器”
- 1.5-Throwables:簡化異常和錯誤的傳播與檢查
- 2-集合
- 2.1-不可變集合
- 2.2-新集合類型
- 2.3-強大的集合工具類:java.util.Collections中未包含的集合工具
- 2.4-集合擴展工具類
- 3-緩存
- 4-函數式編程
- 5-并發
- 5.1-google Guava包的ListenableFuture解析
- 5.2-Google-Guava Concurrent包里的Service框架淺析
- 6-字符串處理:分割,連接,填充
- 7-原生類型
- 9-I/O
- 10-散列
- 11-事件總線
- 12-數學運算
- 13-反射