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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值