Guava ListenableFuture 小試牛刀



Concurrency is a hard problem, but it is significantly simplified by working with powerful and simple abstractions. To simplify matters, Guava extends the Future interface of the JDK with ListenableFuture.


We strongly advise that you always use ListenableFuture instead of Future in all of your code, because:

  • Most Futures methods require it.
  • It's easier than changing to ListenableFuture later.
  • Providers of utility methods won't need to provide Future and ListenableFuture variants of their methods.

併發是一個很難解決的問題,但是通過強有力而簡單抽象又可以變成非常容易。爲了簡化問題,,Google Guava 工具類通過ListenableFuture 繼續JDK  Future  接口實現。


Google  Guava 強烈建議用戶使用ListenableFuture來替代JDK 的Future.


Future  Interface :


A traditional Future represents the result of an asynchronous computation:a computation that may or may not have finished producing a result yet.

Future can be a handle to an in-progress computation, a promise from a service to supply us with a result.


ListenableFuture allows you to register callbacks to be executed once the computation is complete, or if the computation is already complete, immediately.


This simple addition makes it possible to efficiently support many operations that the basic Future interface cannot support.


The basic operation added by ListenableFuture is addListener(Runnable, Executor), which specifies that when the computation represented by this Future is done, the specified Runnablewill be run on the specified Executor.

傳統Future 代表着一個異步計算的結果。一個異步計算也有有結果,也許根本就沒有結果返回。

一個Future可以處理正在進行的計算,一個Promise 可以告訴異步計算的結果。

在Google  Guava 中一個ListenableFuture 允許用戶註冊一個回調函數,這個回調函數會在異步計算完成時被調用。或者異步計算已經完成時,立即被調用。


註冊一個回調函數可以高效的支持很多操作,這個是JDK  Future 接口不提供的功能。


在ListenableFuture接口中有一個addListener(Runnable,Executor)方法。



		ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());

		ListenableFuture<Integer> f = service.submit(new Callable<Integer>() {

			public Integer call() throws Exception {
				Thread.sleep(1000);

				System.out.println("Sleep......");
				return new Integer(99);
			}
		});

		Futures.addCallback(f, new FutureCallback<Integer>() {

			public void onFailure(Throwable arg0) {
				// TODO Auto-generated method stub

			}

			public void onSuccess(Integer arg0) {
				System.out.println("result:" + arg0);

			}
		});
	



參考鏈接:

Guava   ListenableFuture

https://github.com/google/guava/wiki/ListenableFutureExplained


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章