异步神器CompletableFuture

阅读: 评论:0

异步神器CompletableFuture

异步神器CompletableFuture

 

介绍

上个礼拜我们线上有个接口比较慢,这个接口在刚开始响应时间是正常的。但随着数据量的增多,响应时间变慢了。

这个接口里面顺序调用了2个服务,且2个服务之间没有数据依赖。我就用CompletableFuture把调用2个服务的过程异步化了一下,响应时间也基本上缩短为原来的一半,问题解决。

 

正好上次分享了函数式接口和Stream的使用,这次就分享一下CompletableFuture,里面也用到了大量的函数式接口

想方便的异步执行任务,就必须放到单独的线程中。继承Thread类,实现Runnable都不能拿到任务的执行结果,这时就不得不提创建线程的另一种方式了,实现Callable接口。

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}

Callable接口一般配合ExecutorService来使用

// ExecutorService.java
<T> Future<T> submit(Callable<T> task);
ExecutorService executor =&wCachedThreadPool();
Future<Integer> result = executor.submit(() -> {
    int sum = 0;
    for (int i = 0; i < 100; i++) {
        sum += i;    }    return sum;
});// 4950
System.out.());

我们从Future中获取结果

public interface Future<V> {
 // 取消任务的执行
    boolean cancel(boolean mayInterruptIfRunning); // 任务是否已经取消
    boolean isCancelled(); // 任务是否已经完成
    boolean isDone(); // 获取任务执行结果,会阻塞线程
    V get() throws InterruptedException, ExecutionException; // 超时获取任务执行结果,会阻塞线程
    V get(long timeout, TimeUnit unit)        throws InterruptedException, ExecutionException, Timeou

本文发布于:2024-01-31 23:06:24,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170671358732042.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23