MST

星途 面试题库

面试题:Java中CompletableFuture的thenCompose方法使用场景

请描述Java中CompletableFuture的thenCompose方法通常在哪些场景下会被使用,并给出一个简单的代码示例,展示如何使用thenCompose方法将两个异步任务进行组合,其中第一个任务返回一个字符串,第二个任务接收这个字符串并返回一个整数。
23.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

适用场景

thenCompose 方法通常用于需要将两个异步任务进行链式组合,其中第二个任务的输入依赖于第一个任务的输出的场景。这种场景下,使用 thenCompose 可以避免回调地狱,使异步代码更加清晰和易于维护。

代码示例

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> "Hello")
                .thenCompose(s -> processString(s))
                .thenAccept(System.out::println)
                .join();
    }

    private static CompletableFuture<Integer> processString(String input) {
        return CompletableFuture.supplyAsync(() -> input.length());
    }
}

在上述代码中:

  1. CompletableFuture.supplyAsync(() -> "Hello") 创建并异步执行第一个任务,该任务返回字符串 "Hello"
  2. thenCompose(s -> processString(s)) 将第一个任务的结果作为参数传递给 processString 方法,processString 方法返回一个新的 CompletableFuture,该 CompletableFuture 异步计算字符串的长度。
  3. thenAccept(System.out::println) 处理最终结果并打印。
  4. join() 等待整个异步操作链完成。