首页 > 编程语言 >Java多线程CompletableFuture使用

Java多线程CompletableFuture使用

时间:2024-06-12 09:31:20浏览次数:18  
标签:异步 return 任务 future CompletableFuture Java 多线程 public

引言

一个接口可能需要调用N个其他服务的接口,这在项目开发中非常常见。如果是串行执行的话,接口的响应速度会很慢。考虑到这些接口之间有大部分都是无前后顺序关联的,可以并行执行。就比如说调用获取商品详情的时候,可以同时调用获取物流信息,通过并行执行多个任务的方式,接口的响应速度会得到大幅度优化。

在这里插入图片描述

对于存在前后顺序关系的接口调用,可以进行编排,如下所示
在这里插入图片描述

  • 获取用户信息之后,才能调用商品详情和物流信息接口。
  • 成功获取商品详情和物流信息之后,才能调用商品推荐接口。

对于Java程序来说,Java8 引入的CompletableFuture可以帮助我们做多个任务的编排,功能非常强大。

Future介绍

Future类是异步思想的典型运用,主要用在一些需要执行耗时任务的场景,避免程序一直原地等待耗时任务执行完成。执行效率太低。具体来说:当我们执行一个耗时的任务时,可以将这个耗时任务交给一个子线程去异步执行,同时,我们可以干点其他事情,不用等待耗时任务执行完成。等我们其他事情做完,再通过Future类获取耗时任务的执行结果。 这样一来,程序的执行效率就明显提高了。

这其实就是多线程中经典的Future模式。核心思想是异步调用,主要用在多线程的领域。

在Java中,Future类只是一个泛型接口,位于java.util.concurrent 包下,其中定义了 5 个方法,主要包括下面这 4 个功能:

  • 取消任务
  • 判断任务是否被取消
  • 判断任务是否已经执行完成
  • 获取任务执行结果
// V 代表了Future执行的任务返回值的类型
public interface Future<V> {
    // 取消任务执行
    // 成功取消返回 true,否则返回 false
    boolean cancel(boolean mayInterruptIfRunning);
    // 判断任务是否被取消
    boolean isCancelled();
    // 判断任务是否已经执行完成
    boolean isDone();
    // 获取任务执行结果
    V get() throws InterruptedException, ExecutionException;
    // 指定时间内没有返回计算结果就抛出 TimeOutException 异常
    V get(long timeout, TimeUnit unit)
     throws InterruptedException, ExecutionException, TimeoutExceptio
}

CompletableFuture介绍

Future在实际使用过程中存在一些局限性比如不支持异步任务的编排组合、获取计算结果的get()方法为阻塞调用。

Java8 引入了CompletableFuture类可以解决Future的这些缺陷。CompletableFuture除了提供更为好用和强大的Future特性之外,还提供了函数式编程、异步任务编排组合(可以将多个任务串联起来,组成一个完整的链式调用)等能力。

public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {
}

CompletableFuture同时实现了Future和CompletionStage接口。CompletionStage接口描述了一个异步计算的阶段,很多计算可以分成多个阶段或步骤。此时可以通过他将所有步骤组合起来,形成异步计算的流水线。

CompletionStage接口中的方法比较多,CompletableFuture的函数式能力就是这个接口赋予的,从这个接口的方法参数可以发现其大量使用了Java8 引入的函数式编程。

在这里插入图片描述

CompletableFuture常见操作

创建CompletableFuture

常见的常见CompletableFuture对象的方法如下:

  1. 通过new关键字
  2. 基于CompletableFuture自带的静态工厂方法:runAsync()、supplyAsync()。

new 关键字

代码示例

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExample {
    public static void main(String[] args) {
        // 创建一个CompletableFuture对象,初始值为null
        CompletableFuture<String> resultFuture = new CompletableFuture<>();
        // 模拟异步任务
        new Thread(() -> {
            // 这里模拟一个耗时操作
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 异步任务完成,设置结果到CompletableFuture中
            resultFuture.complete("Hello, CompletableFuture!");
        }).start();

        // 当异步任务完成时调用该方法
        resultFuture.thenAccept(result -> System.out.println("异步任务完成,结果为: " + result));
        // 等待异步任务完成并获取结果
        try {
            String result = resultFuture.get();
            System.out.println("获取到异步任务的结果: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

说明
通过new关键字创建CompletableFuture对象这种使用方式可以看作是将CompletableFuture当作Future来使用。可以把resultFuture当作是一部运算结果的载体。

 CompletableFuture<String> resultFuture = new CompletableFuture<>();

假设在某个时刻,我们得到了最终的结果,这时,我们可以调用complete()方法为其传入结果,这表示resultFuture已经计算完成。

 resultFuture.complete("Hello, CompletableFuture!");

也可以通过isDone()方法来检查是否已经完成。

public boolean isDone() {
    return result != null;
}

获取异步计算的结果也非常简单,调用get()方法即可。调用get()方法的线程会阻塞直到CompletableFuture完成计算。

String result = resultFuture.get();

静态工厂方法

这两个方法可以帮助我们封装计算逻辑

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
// 使用自定义线程池(推荐)
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor);
static CompletableFuture<Void> runAsync(Runnable runnable);
// 使用自定义线程池(推荐)
static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor);

runAsync()方法接受的参数是Runnable,这是一个函数式接口,不允许返回值。当你需要异步操作且不关心返回结果时候使用。

supplyAsync()方法接受的参数是Supplier< U >,这也是一个函数式接口,U是返回结果值的类型。当需要异步操作且关心返回结果的时候,可以使用supplyAsync()方法。

使用示例:

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("hello!"));
future.get();// 输出 "hello!"
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello!");
assertEquals("hello!", future2.get());

处理异步计算结果

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法如下:

  • thenApply() : 当CompletableFuture完成时,将异步计算结果作为参数传递给指定的函数,并返回一个新的CompletableFuture作为异步结果。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<String> resultFuture = future.thenApply(i -> "Result: " + i);
System.out.println(resultFuture.get()); // 输出 "Result: 10"
  • thenAccept():当CompletableFuture完成时,将异步计算结果作为参数传递给指定的消费者函数,不返回任何结果。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10);
future.thenAccept(i -> System.out.println("Result: " + i));
  • thenRun():当CompletableFuture完成时,执行指定的Runnable动作,不接受异步计算结果。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10);
future.thenRun(() -> System.out.println("Done!"));
  • whenComplete():当CompletableFuture完成时,指定指定的动作,无论异步任务是否发生异常都会执行该操作
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10 / 0);
future.whenComplete((result, exception) -> {
    if (exception != null) {
        System.out.println("Exception occurred: " + exception.getMessage());
    } else {
        System.out.println("Result: " + result);
    }
});

1. thenApply()

方法接受一个Function实例,用它来处理结果。

// 沿用上一个任务的线程池
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn) {
    return uniApplyStage(null, fn);
}

//使用默认的 ForkJoinPool 线程池(不推荐)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn) {
    return uniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor) {
    return uniApplyStage(screenExecutor(executor), fn);
}

使用示例如下:
实例一:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
        .thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。
future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

实例二:还可以进行流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
        .thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果不需要从回调函数中获取返回结果,可以使用thenAccept()或者thenRun()。这两个方法的区别在于thenRun不能访问异步计算的结果。

2. thenAccpet()
方法的参数是 Consumer<? super T> action,将异步计算结果作为参数传递给指定的消费者函数。

public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
    return uniAcceptStage(null, action);
}

public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
    return uniAcceptStage(defaultExecutor(), action);
}

public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
                                               Executor executor) {
    return uniAcceptStage(screenExecutor(executor), action);
}

3. thenRun()
方法参数是Runnable,不能访问异步计算的结果,只能在异步计算完成后,继续其他操作。

public CompletableFuture<Void> thenRun(Runnable action) {
    return uniRunStage(null, action);
}

public CompletableFuture<Void> thenRunAsync(Runnable action) {
    return uniRunStage(defaultExecutor(), action);
}

public CompletableFuture<Void> thenRunAsync(Runnable action,
                                            Executor executor) {
    return uniRunStage(screenExecutor(executor), action);
}

4. whenComplete()
whenComplete() 的方法的参数是 BiConsumer<? super T, ? super Throwable> 。

public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) {
    return uniWhenCompleteStage(null, action);
}
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action) {
    return uniWhenCompleteStage(defaultExecutor(), action);
}
// 使用自定义线程池(推荐)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, 
Executor executor) {
    return uniWhenCompleteStage(screenExecutor(executor), action);
}

BiConsumer可以接受两个输入对象然后进行消费,BiConsumer<? super T, ? super Throwable>
第一个参数

?super T : 父类为CompletableFuture创建时使用泛型T 定义的返回结果类型。传入异步计算结果。
?super Throwable:父类为Throwable,即异步计算结果抛出异常时,该字段不为空。

处理异常

可以通过handle()方法来处理任务执行过程中可能出现的异常情况。

public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn) {
    return uniHandleStage(null, fn);
}

public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn) {
    return uniHandleStage(defaultExecutor(), fn);
}

public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, 
Executor executor) {
    return uniHandleStage(screenExecutor(executor), fn);
}

示例代码:

CompletableFuture<String> future= CompletableFuture.supplyAsync(() -> {
    if (true) {
        throw new RuntimeException("Computation error!");
    }
    return "hello!";
}).handle((res, ex) -> {
    // res 代表返回的结果
    // ex 的类型为 Throwable ,代表抛出的异常
    return res != null ? res : "world!";
});
assertEquals("world!", future.get());

还可以通过 exceptionally() 方法来处理异常情况。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    if (true) {
        throw new RuntimeException("Computation error!");
    }
    return "hello!";
}).exceptionally(ex -> {
    System.out.println(ex.toString());// CompletionException
    return "world!";
});
assertEquals("world!", future.get());

如果想让CompletableFuture结果就是异常的话,可以使用completeExceptionally()为其赋值。

CompletableFuture<String> completableFuture = new CompletableFuture<>();
// ...
completableFuture.completeExceptionally(
  new RuntimeException("Calculation failed!"));
// ...
completableFuture.get(); // ExecutionException

组合CompletableFuture

可以使用thenCompose() 按顺序链接两个completableFuture对象,实现异步的任务链。他的作用是将前一个任务的返回结果作为下一个任务的输入参数,从而形成一个依赖关系。

public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn) {
    return uniComposeStage(null, fn);
}

public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn) {
    return uniComposeStage(defaultExecutor(), fn);
}

public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn,
    Executor executor) {
    return uniComposeStage(screenExecutor(executor), fn);
}

使用示例:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello!")
        .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "world!"));
assertEquals("hello!world!", future.get());

在实际开发中,这个方法还是非常有用的,比如,task1和task2都是异步执行,但是task1必须执行完成后才能开始执行task2(task2依赖task1的执行结果)。
和thenCompose()类似的还有thenCombine(),他同样可以组合两个CompletableFuture对象。

CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "hello!")
        .thenCombine(CompletableFuture.supplyAsync( () -> "world!"), (s1, s2) -> s1 + s2)
        .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "nice!"));
assertEquals("hello!world!nice!", completableFuture.get());

thenCompose()和thenCombine()有什么区别

  • thenCompose()可以链接两个completableFuture对象,并将前一个任务的结果作为下一个任务的参数,他们之间存在先后关系。
  • thenCombine() 会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的。他们之间没有先后依赖关系。

除了thenCompose()、thenCombine() 之外,还有一些其他的组合completableFuture方法用于实现不同的效果,满足不同的业务需求。

例如,如果我们想要实现task1和task2中的任意一个任务后就可以执行task3的话,可以使用acceptEither().

public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action) {
    return orAcceptStage(null, other, action);
}

public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action) {
    return orAcceptStage(asyncPool, other, action);
}

示例程序:

CompletableFuture<String> task = CompletableFuture.supplyAsync(() -> {
    System.out.println("任务1开始执行,当前时间:" + System.currentTimeMillis());
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("任务1执行完毕,当前时间:" + System.currentTimeMillis());
    return "task1";
});

CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
    System.out.println("任务2开始执行,当前时间:" + System.currentTimeMillis());
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("任务2执行完毕,当前时间:" + System.currentTimeMillis());
    return "task2";
});

task.acceptEitherAsync(task2, (res) -> {
    System.out.println("任务3开始执行,当前时间:" + System.currentTimeMillis());
    System.out.println("上一个任务的结果为:" + res);
});

// 增加一些延迟时间,确保异步任务有足够的时间完成
try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

输出:

任务1开始执行,当前时间:1695088058520
任务2开始执行,当前时间:1695088058521
任务1执行完毕,当前时间:1695088059023
任务3开始执行,当前时间:1695088059023
上一个任务的结果为:task1
任务2执行完毕,当前时间:1695088059523

任务组合操作acceptEitherAsync()会在异步任务1和异步任务2中的任意一个完成时出发执行任务3.但需要注意,这个触发时机不确定。

并行运行多个CompletableFuture

可以通过CompletableFuture的allOf()这个静态方法来并行运行多个CompletableFuture。

实际项目中,我们经常需要并行运行多个互不相关的任务。这些任务之间没有依赖关系,可以互相独立的运行。

比如,我们需要读取处理6个文件,这6个任务都是没有执行顺序依赖的任务,但是我们需要返回给用户的时候将这几个文件的处理结果进行统计整理,这种情况我们可以使用并行运行多个CompletableFuture来处理。

示例如下:

CompletableFuture<Void> task1 = CompletableFuture.supplyAsync(()->{
    //自定义业务操作
  });
......
CompletableFuture<Void> task6 = CompletableFuture.supplyAsync(()->{
    //自定义业务操作
  });
......
 CompletableFuture<Void> headerFuture=CompletableFuture.allOf(task1,.....,task6);
  try {
    headerFuture.join();
  } catch (Exception ex) {
    ......
  }
System.out.println("all done. ");

经常和allOf()方法对比的是anyOf()方法。

allOf()方法会等到所有的CompletableFuture都运行完成之后在返回。调用join方法让task1。。。。task6都运行完之后在继续执行
anyOf方法不会等待所有的CompletableFuture都运行完成之后在返回,只要有一个执行完成即可。

CompletableFuture使用建议

使用自定义线程池

CompletableFuture默认使用ForkJoinPool.commonPool()作为执行器,这个线程池是全局共享的,可能会被其他任务占用,导致性能下降或者饥饿。建议使用自定义的线程池来执行CompletableFuture的异步任务,可以提高并发度和灵活性。

private ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>());

CompletableFuture.runAsync(() -> {
     //...
}, executor);

尽量避免使用get()

CompletableFuture的get()方法是阻塞的,尽量避免使用。如果必须使用的话,需要添加超时时间,否则可能会导致主线程一直等待,无法执行其他任务。

    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(10_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Hello, world!";
    });

    // 获取异步任务的返回值,设置超时时间为 5 秒
    try {
        String result = future.get(5, TimeUnit.SECONDS);
        System.out.println(result);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        // 处理异常
        e.printStackTrace();
    }
}

上面这段代码在调用get()时抛出TimeoutException,我们可以在异常处理中进行相应的操作,如取消任务、重试任务、记录日志等。

正确进行异常处理

使用 CompletableFuture的时候一定要以正确的方式进行异常处理,避免异常丢失或者出现不可控问题。

  • 使用whenComplete方法可以在任务完成时触发回调函数,并正确处理异常,而不是让异常被吞噬或丢失。
  • 使用exceptionally方法可以处理异常并重新抛出,以便异常能够传播到后续阶段,而不是让异常被忽略或者终止。
  • 使用handle方法可以处理正常的返回结果和异常,并返回一个新的结果,而不是让异常影响整体的逻辑。
  • 使用CompletableFuture.allOf方法可以组合多个CompletableFuture,并统一处理所有任务的异常,而不是让异常处理过于冗长或者重复。

合理组合多个异步任务

正确使用thenCompose()、thenCombine()、acceptFilter()、allOf()、anyOf()等方法来组合多个异步任务,以满足实际业务需求,提高程序执行效率。

在这里插入图片描述

标签:异步,return,任务,future,CompletableFuture,Java,多线程,public
From: https://blog.csdn.net/weixin_42824596/article/details/139598224

相关文章

  • 计算机毕业设计项目推荐,32127 爬虫-自驾游搜索系统(开题答辩+程序定制+全套文案 )上万套
    目 录摘要1绪论1.1研究背景1.2爬虫技术1.3flask框架介绍21.4论文结构与章节安排32 自驾游搜索系统分析42.1可行性分析42.2系统流程分析42.2.1数据增加流程52.3.2数据修改流程52.3.3数据删除流程52.3系统功能分析52.3.1功能性分析62.......
  • 计算机毕业设计项目推荐,32006 node 中国传统节日介绍网站(开题答辩+程序定制+全套文案
    基于node.js中国传统节日介绍网站 摘 要随着科学技术的飞速发展,社会的方方面面、各行各业都在努力与现代的先进技术接轨,通过科技手段来提高自身的优势,中国传统节日介绍网站当然也不能排除在外。中国传统节日介绍网站是以实际运用为开发背景,运用软件工程原理和开发方法,采......
  • 计算机毕业设计项目推荐,29042 基于Web的医院护理管理系统的设计(开题答辩+程序定制+全
    摘 要随着科学技术的飞速发展,社会的方方面面、各行各业都在努力与现代的先进技术接轨,通过科技手段来提高自身的优势,医院当然也不例外。医院预约管理系统是以实际运用为开发背景,运用软件工程原理和开发方法,采用Java技术构建的一个管理系统。整个开发过程首先对软件系统进......
  • 怎么理解Java里的双冒号 “::”
    ​ “::”是什么?在java中,双冒号“::”是方法引用的语法。方法引用是简化Lambda表达式的语法结构,使代码更简洁易懂,并且在使用引用方法时,会根据上下文推断参数类型,因此特别适用于直接引用已有方法的情况。“::”的用法 1ClassName::MethodName 其实,Class是包含静态方法me......
  • java面试题: HashMap、HashSet 和 HashTable 的区别
     HashMap常用方法 HashMap是一个基于哈希表的Map接口的实现。它允许使用null值和null键。 java复制//创建一个HashMapHashMap<KeyType,ValueType>map=newHashMap<>(); //添加元素map.put(key,value); //获取元素ValueTypevalue=map.get......
  • 【java攻城狮的一生:第一站—JDK安装】
    文章目录概要下载官方网址百度网盘(我这里只提供了我用到的)安装验证结果概要没啥概要,就是下载->安装->验证结果......
  • JavaEE
    JavaEE架构程序设计实验作业实验名称:一、实验项目功能使用Struts2+Hibernate+Spring结构完成了完整的学生信息管理系统,其中包括成绩管理、学生管理、课程管理、专业管理、班级管理。   二、实验过程使用Struts2+Hibernate+Spring结构完成了完整的学生信息管理......
  • 什么是Java泛型,它的优点是什么?
    什么是Java泛型?Java泛型(Generics)是一种使得类、接口和方法能够操作任意类型(类型参数化)的机制。它允许我们在编写代码时使用类型参数,从而使代码更加通用和灵活。泛型的主要目的是在编译时提供类型安全检查,并消除类型转换的需要。在Java5之前,集合类(如List、Set、Map)只能存储O......
  • 力控算法每日一练:209. 长度最小的子数组(java)
    给定一个含有 n 个正整数的数组和一个正整数 target 。找出该数组中满足其总和大于等于 target 的长度最小的 子数组 [numsl,numsl+1,...,numsr-1,numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。classSolution{publicintminSubArrayL......
  • 【练习代码】6.11 java学习记录:继承与多态(实例:媒体资料库的设计)
    设计一个媒体资料库,能存入不同类别的媒体资料,例如CD与DVD,并且能完成添加与列表等操作,需要些什么?最基础的想法一个代表整体库的DataBase类,内部的属性包括CD和DVD的Arraylist,对应操作通过定义自己的方法来实现,部分代码如下:publicclassDatabase{privateArrayList<CD>......