Google Guava的Future

1 介绍

Future虽然为我们提供了一个凭据,但是在未来某个时间节点进行get()操作时仍然会使当前线程进入阻塞,显然这种操作方式并不是十分完美,因此在Google Guava并发包中提供了对异步任务执行的回调支持,它允许你注册回调函数而不用再通过get()方法苦苦等待异步任务的最终计算结果(Don’t Call Us, We’ll Call You!)

2 ListenableFuture(可监听的的Future)

Guava提供了ListneningExecutorService,使用该ExecutorService提交执行异步任务时将返回ListenableFuture,通过该Future,我们可以注册回调接口。

public interface ListeningExecutorService extends ExecutorService

示例代码:

public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    // 通过 MoreExecutors定义ListeningExecutorService
    ListeningExecutorService listeningDecorator = MoreExecutors.listeningDecorator(executorService);

    // 提交任务
    ListenableFuture<String> future = listeningDecorator.submit(() -> {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hello";
    });
    // 注册监听
    future.addListener(()->{
        try {
            // 获取任务结果
            String res = future.get();
            System.out.println("任务执行完毕,结果 -> " + res);
            
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    },listeningDecorator);
}

3 FutureCallback

除了ListenableFuture之外,还可以注册FutureCallback,相比前者用Runnable接口作为回调接口,FutureCallback提供的回调方式则更为直观

示例:

public static void main(String[] args) {
     ExecutorService executorService = Executors.newCachedThreadPool();
     // 通过 MoreExecutors定义ListeningExecutorService
     ListeningExecutorService listeningDecorator = MoreExecutors.listeningDecorator(executorService);

     // 提交任务
     ListenableFuture<String> future = listeningDecorator.submit(() -> {
         try {
             TimeUnit.SECONDS.sleep(3);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         return "hello";
     });

     // 注册callback
     Futures.addCallback(future, new FutureCallback<String>() {
         @Override
         public void onSuccess(@Nullable String res) {
             System.out.println("任务执行成功,结果是 ->" + res);
         }

         @Override
         public void onFailure(Throwable throwable) {
             System.out.println("任务执行失败");
         }
     },listeningDecorator);
 }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值