Skip to content

9. 异步编程

上一章介绍了线程:我们可以“同时”执行多段代码,对它们进行同步,并通过执行器([ExecutorService])把任务分配给线程池。本章讨论一个相关但不同的问题:如何编写一个需要大量等待(等待磁盘、网络或数据库)的程序,而又不会在这些等待期间占用线程。

Java 没有用于此目的的语言关键字(其他语言,如 C# 或 JavaScript,有关键字 [async] 和 [await])。它提供了两种相互补充的解决方案,本章都会介绍:

  • [CompletableFuture<T>] 类(Java 8,此后有所增强)表示一个正在进行的操作,其后续步骤通过回调方法进行组合:“当结果就绪时,先做这个,再做那个”([thenApply]、[thenCompose]、[thenCombine]、[allOf]……)。没有线程在等待:由操作的完成触发下一步;
  • 另一方面,虚拟线程(Java 21)允许你编写阻塞式、自上而下阅读的顺序代码:当虚拟线程等待输入/输出时,JVM 会把它从执行它的系统线程(其“载体线程”)上分离,并释放该线程供另一个虚拟线程使用。这使得只需几个系统线程就可以拥有数十万个虚拟线程。这是 Java 针对其他语言用 [async] / [await] 来解决的问题所给出的现代方案。

这些工具如今无处不在:后续章节将用它们来访问数据库、编写通过虚拟线程为每个客户端提供服务的 TCP 服务器、使用 [java.net.http.HttpClient] 的 Web 客户端,以及使用 Spring Boot 的 Web 服务。

本章的所有示例都是紧凑源文件([Async01.java]、[Async02.java]……),在 [09-async] 文件夹中使用 [java AsyncNN.java] 运行。其中许多示例使用 [System.nanoTime()] 测量执行时间:显示的毫秒数在每次运行和每台机器之间都会有所不同(这些示例是在一台双处理器机器上运行的)。重要的是数量级:是 1 秒还是 10 秒,是 300 毫秒还是 0 毫秒。

9.1. 为什么需要异步

9.1.1. 会等待的操作

程序执行两类工作:

  • 计算任务,占用处理器:对列表排序、计算税款、分析文本;
  • 输入/输出 (I/O),本质上就是等待外围设备:从磁盘读取文件、向 Web 服务器发送请求并等待其响应、在数据库服务器上执行 SQL 查询。

它们的数量级差别很大。处理器每秒执行几十亿条指令。磁盘(SSD)上的一次读操作大约需要十分之一毫秒;一次局域网往返只需不到一毫秒;到位于国家另一端的服务器的一次往返需要几十毫秒;而一个稍微复杂的 SQL 请求有时可能需要几秒。在这些等待期间,处理器本可以执行数百万条指令。

当程序使用阻塞方法通过网络连接读取一行数据时,执行这次读取的线程会被阻塞:它什么也不做,但仍然存在。“经典”的 Java 线程——现在称为“平台线程”——就是操作系统线程:它占用内存(其栈,大约一兆字节),被系统所识别,而且最重要的是,它无法再去做其他事情。在一次只做一件事的小型控制台程序中,这不是问题。但在两种情况下,问题就严重得多:

  • 在服务器中:每个由被阻塞线程服务的客户端都会占用一个线程。如果服务器的线程池有 N 个线程,而这 N 个线程都在执行阻塞操作,就没有空闲线程可供新客户端使用。现代服务器可以处理数千个同时到来的请求:之所以能做到,是因为它的等待操作不会占用系统线程;
  • 在图形用户界面中:由单个线程(UI 线程,即 Swing 的“事件分派线程”、“JavaFX 应用程序线程”)处理点击和窗口重绘。如果它被下载操作阻塞,窗口就会冻结。

异步的做法是发起 I/O 操作,在其进行期间释放系统线程(硬件和操作系统传输数据并不需要它),然后在操作完成后恢复工作,可能是在另一个系统线程上:

Image

  • 在 [1] 中,平台线程 T1 发起 I/O,并一直阻塞到它结束;
  • 在 [2] 中,虚拟线程 V1 发起 I/O;JVM 把它从其载体线程 P1 上分离,P1 随即可以立即执行其他虚拟线程。当 I/O 完成时,JVM 把 V1 重新挂载到一个空闲的载体线程 P2(也可能就是 P1)上,V1 在阻塞指令之后立即继续执行,就好像什么都没发生过一样。

程序 [Async01.java] 测量了 100 个操作的差异,每个操作等待一秒(等待用来模拟 I/O)。它使用了我们将在本章后面解释的指令([Executors.newVirtualThreadPerTaskExecutor]、[CompletableFuture]):在这里,我们主要关心的是结果。

// 为什么要异步:100 个操作,每个都等待一秒
// (等待模拟 I/O:磁盘读取、网络请求、SQL 查询……)
import java.lang.management.ManagementFactory;

final int nbOperations = 100;
long start;

void main() throws InterruptedException {
    IO.println(nbOperations + " operations of one second, "
            + Runtime.getRuntime().availableProcessors() + " processors");

    // 1 - 每个操作一个平台线程,每个线程在等待期间被阻塞
    start = System.nanoTime();
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < nbOperations; i++) {
        threads.add(Thread.ofPlatform().start(() -> waitFor(1000)));
    }
    display("1 - one platform thread per operation", jvmThreads());
    for (Thread thread : threads) {
        thread.join();
    }
    display("    end", -1);

    // 2 - 操作交给一个 10 个线程的线程池,但它们会阻塞线程池
    start = System.nanoTime();
    try (ExecutorService pool = Executors.newFixedThreadPool(10)) {
        for (int i = 0; i < nbOperations; i++) {
            pool.submit(() -> waitFor(1000));
        }
        display("2 - pool of 10 threads, blocking waits", jvmThreads());
    } // close() 等待所有操作结束
    display("    end", -1);

    // 3 - 每个操作一个虚拟线程:它在等待期间释放其载体线程
    start = System.nanoTime();
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        for (int i = 0; i < nbOperations; i++) {
            executor.submit(() -> waitFor(1000));
        }
        display("3 - one virtual thread per operation", jvmThreads());
    }
    display("    end", -1);

    // 4 - 异步等待:没有线程在等待,由定时器完成每个操作
    start = System.nanoTime();
    var operations = new CompletableFuture<?>[nbOperations];
    for (int i = 0; i < nbOperations; i++) {
        operations[i] = new CompletableFuture<Void>().completeOnTimeout(null, 1000, TimeUnit.MILLISECONDS);
    }
    display("4 - asynchronous waits (CompletableFuture)", jvmThreads());
    CompletableFuture.allOf(operations).join();
    display("    end", -1);
}

// 阻塞等待 [ms] 毫秒
void waitFor(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

// 操作启动半秒后 JVM 的平台线程数
int jvmThreads() {
    long elapsed = (System.nanoTime() - start) / 1_000_000;
    if (elapsed < 500) {
        waitFor(500 - elapsed);
    }
    return ManagementFactory.getThreadMXBean().getThreadCount();
}

// 显示耗时,以及(若提供,>= 0)线程数
void display(String message, int nbThreads) {
    String threadsInfo = nbThreads < 0 ? "" : String.format(", %3d threads in the JVM", nbThreads);
    long elapsed = (System.nanoTime() - start) / 1_000_000;
    IO.println(String.format("%-44s : %5d ms%s", message, elapsed, threadsInfo));
}

结果:

> java Async01.java
100 operations of one second, 2 processors
1 - one platform thread per operation        :   534 ms, 106 threads in the JVM
    end                                      :  1061 ms
2 - pool of 10 threads, blocking waits       :   501 ms,  16 threads in the JVM
    end                                      : 10021 ms
3 - one virtual thread per operation         :   501 ms,  10 threads in the JVM
    end                                      :  1091 ms
4 - asynchronous waits (CompletableFuture)   :   500 ms,  11 threads in the JVM
    end                                      :  1003 ms

说明:

  • 第 12–22 行:最简单的方案——每个操作一个平台线程。[Thread.ofPlatform().start(task)] (Java 21)创建并启动一个线程,就像 [new Thread(task).start()] 一样。每个线程执行 [Thread.sleep(1000)]:它被阻塞一秒钟。这 100 次等待同时发生,整个过程恰好耗时一秒(结果的第 4 行),但代价是多出 100 个系统线程:JVM 共有 106 个(第 3 行)。如果有 10,000 个操作,就需要 10,000 个系统线程;
  • 第 24–32 行:操作被分配给一个 10 线程的线程池([Executors.newFixedThreadPool(10)]),对计算来说这是一个合理的大小。但这里,这些线程并没有在计算——它们在空闲等待。操作以 10 个为一批等待空闲线程,整个过程耗时……十秒(第 6 行)。这被称为“线程池饥饿”,是把线程池与阻塞式 I/O 混用的服务器中最常见的缺陷。执行器的 [close()] 方法(Java 19)在退出 [try] 时被调用,它拒绝新任务,并等待已提交的任务完成;
  • 第 34–42 行:每个操作一个虚拟线程。[Executors.newVirtualThreadPerTaskExecutor()] (Java 21)返回一个为每个提交的任务创建新虚拟线程的执行器。任务代码与步骤 1 中相同:一个阻塞的 [Thread.sleep(1000)]。然而,被阻塞的虚拟线程不会占用系统线程:JVM 把它从载体线程上分离。这 100 次等待总共持续一秒(第 8 行),而 JVM 只统计到 10 个系统线程(第 7 行):它自己的服务线程,以及执行这 100 个虚拟线程的两个载体线程——每个处理器一个。虚拟线程不计入这个数目:它们是 JVM 的对象,而不是系统线程;
  • 第 44–52 行:同样的等待,但没有线程在等待。[new CompletableFuture<Void>()] 创建一个“待定”的操作,而 [completeOnTimeout(value, timeout, unit)] (Java 9)要求在超时到期时用指定的值完成它。由 JVM 的单个定时器管理这 100 个超时。[CompletableFuture.allOf(...)] 返回一个在所有其他操作完成时完成的操作,而 [join()] 等待它结束。整个过程持续一秒(第 10 行),与步骤 3 相比只多了一个线程——定时器线程(第 9 行);
  • 第 55–62 行:[Thread.sleep] 如果线程在休眠期间被中断,可能抛出受检异常 [InterruptedException] (我们将在取消一节中进一步讨论);[waitFor] 方法拦截了它,这样第 16、28 和 38 行的 lambda 就不必处理它;
  • 第 64–71 行:[ManagementFactory.getThreadMXBean().getThreadCount()] 返回 JVM 的存活平台线程数。[ManagementFactory] 类属于模块 [java.management]:紧凑源文件只会自动导入模块 [java.base],因此才有第 3 行的导入。

让我们记住这个教训:要等待,就不能阻塞任何系统线程。异步并不会让 I/O 变得更快;它让你可以用很少的系统线程同时处理大量 I/O 操作,同时保持应用程序所需的线程可用。Java 为此提供了两种方法:创建 [CompletableFuture] (步骤 4),或者编写由虚拟线程执行的普通阻塞代码(步骤 3)。

9.1.2. 几种先后出现的模型

Java 提供过几种编写等待而不阻塞的代码的方式。较早的方式仍然出现在现有代码中,因此认识它们是有益的。

模式
引入版本
原理
[Future] 与运行时
Java 5(2004)
[ExecutorService.submit] 把任务分配给线程池,并返回一个 [Future<T>],它代表即将得到的结果。但获得该结果的唯一方式是通过 [get()] 阻塞等待。
NIO.2 的回调方法
Java 7(2011)
异步通道 ([AsynchronousSocketChannel]、[AsynchronousFileChannel])发起一个操作并接收一个回调对象([CompletionHandler]),操作完成后,由线程池中的线程调用其方法 [completed] 或 [failed]。
[CompletableFuture]
Java 8(2014)
一种你可以自行终结的 [Future] ,其执行序列由回调方法([thenApply]、[thenCompose]、[exceptionally]……)组合而成;响应式流 [java.util.concurrent.Flow] (Java 9)是它针对值序列的扩展。响应式库(Spring WebFlux 使用的 Project Reactor、RxJava)基于相同的概念。
虚拟线程
Java 21(2023)
普通的阻塞代码,由虚拟线程执行:JVM 在等待期间释放系统线程。这是当今新应用程序推荐使用的模型。
结构化并发
Java 21 至 Java 25 的预览特性
[StructuredTaskScope] 把一组由虚拟线程执行的子任务组织成单个代码块,具有共享的错误处理和取消机制(见本章末尾)。

回调方法有一个缺点:代码是碎片化的。自然读作“连接,然后读取,然后显示”的逻辑,变成了一个发起连接的方法、一个发起读取操作的回调方法,以及另一个显示结果的回调方法;变量必须在这些方法之间共享,异常在不同的位置被捕获,而一个简单的循环(“只要还有数据就读取”)则变成一个递归调用自身的回调方法。[CompletableFuture] 通过把各步骤链接起来,让这种碎片化更易读;虚拟线程则让它消失:异步代码采用同步代码的形式,因为它就是同步代码。

程序 [Async02.java] 用两种极端的方式实现同一个 TCP 客户端:首先使用 NIO.2 的回调方法,然后使用由虚拟线程执行的阻塞代码。它还包含一个由线程运行的小型服务器,用来响应两个客户端(网络编程将在第 12 章详细介绍;目前只需知道客户端连接到服务器并读取服务器发送给它的消息即可)。

// 同一个 TCP 客户端,先用回调方法编写(NIO.2,Java 7),再用虚拟线程编写(Java 21)
final int port = 27500;
final InetAddress local = InetAddress.getLoopbackAddress();
final ByteBuffer buffer = ByteBuffer.allocate(1024);
final CountDownLatch end = new CountDownLatch(1);

void main() throws IOException, InterruptedException {
    // 一个由线程执行的最小服务器:它为两个客户端提供服务,然后停止
    var listener = new ServerSocket(port, 10, local);
    Thread server = Thread.ofPlatform().name("server").start(() -> {
        try (listener) {
            for (int i = 1; i <= 2; i++) {
                try (Socket service = listener.accept()) {
                    // 服务器需要一些时间才回答
                    Thread.sleep(500);
                    byte[] message = ("Hello client no. " + i).getBytes(StandardCharsets.UTF_8);
                    service.getOutputStream().write(message);
                }
            }
        } catch (IOException | InterruptedException e) {
            display("server: " + e);
        }
    });
    display("start of the program");

    // 1 - “回调方法”风格:AsynchronousSocketChannel 和 CompletionHandler
    var client = AsynchronousSocketChannel.open();
    // 我们发起连接,并提供完成后要回调的对象
    client.connect(new InetSocketAddress(local, port), client, new Connected());
    display("callbacks: connection started, the program continues");
    // 主线程已无事可做:它等待最后一个回调方法的信号
    end.await();

    // 2 - 阻塞风格,由虚拟线程执行:代码自上而下阅读
    Thread virtual = Thread.ofVirtual().start(() -> {
        try (var client2 = new Socket(local, port)) {
            display("virtual thread: connected, read started");
            byte[] bytes = new byte[1024];
            int nbBytes = client2.getInputStream().read(bytes);
            String message = new String(bytes, 0, nbBytes, StandardCharsets.UTF_8);
            display("virtual thread: received [" + message + "]");
        } catch (IOException e) {
            display("virtual thread: " + e);
        }
    });
    virtual.join();
    server.join();
}

// 第 1 号回调方法:连接已建立(或已失败)
class Connected implements CompletionHandler<Void, AsynchronousSocketChannel> {
    @Override
    public void completed(Void nothing, AsynchronousSocketChannel channel) {
        display("callbacks: connected, read started");
        // 我们用另一个回调对象开始读取服务器的回答
        channel.read(buffer, channel, new Received());
    }

    @Override
    public void failed(Throwable e, AsynchronousSocketChannel channel) {
        display("callbacks: connection failed: " + e);
        end.countDown();
    }
}

// 第 2 号回调方法:数据已到达
class Received implements CompletionHandler<Integer, AsynchronousSocketChannel> {
    @Override
    public void completed(Integer nbBytes, AsynchronousSocketChannel channel) {
        display("callbacks: received [" + new String(buffer.array(), 0, nbBytes, StandardCharsets.UTF_8) + "]");
        try {
            channel.close();
        } catch (IOException e) {
            display("callbacks: " + e);
        }
        // 我们通知主线程
        end.countDown();
    }

    @Override
    public void failed(Throwable e, AsynchronousSocketChannel channel) {
        display("callbacks: read failed: " + e);
        end.countDown();
    }
}

// 以执行显示的线程为前缀的显示
// (平台线程的名称,虚拟线程的描述)
void display(String message) {
    Thread thread = Thread.currentThread();
    IO.println("[" + (thread.isVirtual() ? thread.toString() : thread.getName()) + "] " + message);
}

结果:

1
2
3
4
5
6
7
> java Async02.java
[main] start of the program
[main] callbacks: connection started, the program continues
[InnocuousThread-4] callbacks: connected, read started
[InnocuousThread-2] callbacks: received [Hello client no. 1]
[VirtualThread[#28]/runnable@ForkJoinPool-1-worker-1] virtual thread: connected, read started
[VirtualThread[#28]/runnable@ForkJoinPool-1-worker-2] virtual thread: received [Hello client no. 2]

说明:

  • 第 8–23 行:服务器。它监听本机的 27500 端口([InetAddress.getLoopbackAddress()],即 127.0.0.1),依次接受两个连接,并在半秒后向每个客户端发送一条欢迎消息。它由一个名为 [server] 的平台线程执行。形式 [try (listener)] (Java 9)会在块结束时关闭第 9 行声明的 [ServerSocket];
  • 第 26–32 行:客户端使用回调方法进行写入:
    • 第 27 行:*[AsynchronousSocketChannel]* 是一个操作为异步的 TCP 通道;
    • 第 29 行:[connect] 发起连接并立即返回控制权(结果的第 3 行)。它的最后两个参数是回调方法将收到的任意对象(这里是通道本身)和类型为 [Connected] 的回调对象;
    • 第 32 行:主线程已无事可做。为了确保程序不会在交互完成之前终止,它等待来自最后一个回调方法的信号:一个初始化为 1 的 [CountDownLatch] (第 5 行),其方法 [await] 会阻塞调用它的线程,直到另一个线程调用其方法 [countDown];
  • 第 50–64 行:连接的回调对象实现了 [CompletionHandler<V, A>] 接口,其中 [V] 是操作的结果类型(连接操作为 [Void]),[A] 是所传入对象的类型。如果操作成功,则调用其方法 [completed];如果失败,则调用其方法 [failed]。连接成功后,通过 [read] 并指定第二个类型为 [Received] 的回调对象来发起读取(第 56 行);
  • 第 66–85 行:读取回调对象接收读取的字节数,显示消息,关闭通道,并释放主线程。类 [Connected] 和 [Received] 是紧凑文件的隐式类的内部类:它们可以访问其字段 [buffer] 和 [end] 以及其方法 [display];
  • 结果表明,回调方法由主线程以外的线程执行(来自 JVM 中专用于异步通道的线程池,名为 [InnocuousThread-N]);
  • 第 34–46 行:同一个客户端,使用标准的 [Socket] 和阻塞操作编写([new Socket(...)] 负责连接,[read] 等待数据),由通过 [Thread.ofVirtual().start(task)] (Java 21)创建的虚拟线程执行。代码像同步代码一样自上而下阅读;变量是普通的局部变量;错误由单个 [try / catch] 处理;没有需要管理的回调方法或信号;
  • 第 87–92 行:每次显示都以执行它的线程作为前缀。对于虚拟线程,[toString()] 返回形如 [VirtualThread[#28]/runnable@ForkJoinPool-1-worker-1] 的描述:虚拟线程编号、它的状态,以及它当前的宿主线程。结果的第 6 行和第 7 行显示的是同一个 28 号虚拟线程,先由 [worker-1] 承载,然后由 [worker-2] 承载:在等待服务器响应期间,它先从第一个载体线程上分离,然后又重新挂载到另一个载体线程上。

没有必要保留 [CompletionHandler] 接口。如果你必须使用只提供这种模型的 API,可以把它转换为 [CompletableFuture] (我们将在 [Async17.java] 中这样做),或者在虚拟线程上使用其阻塞版本。

9.2. 未来的任务:Future 和 CompletableFuture

[Future<T>] ([java.util.concurrent] 包的接口,Java 5)是一个对象,表示一个正在进行或已完成的操作的结果,其类型为 [T]。我们在上一章遇到过它:执行器的 [submit] 方法返回的就是它。你可以查询它(是否已完成?是否成功?)、取消它([cancel])、等待它的结果([get]),但仅此而已:使用结果的唯一方式是阻塞一个线程,直到结果可用。

[CompletableFuture<T>] 类(Java 8)实现了 [Future<T>] 并增加了两项关键能力:

  • 你可以自行终结它,给出一个结果([complete])或一个异常([completeExceptionally]);
  • 你可以为它附加一个后续操作——一个在结果可用时执行的函数([thenApply]、[thenAccept]、[thenCompose]……),它会产生一个新的 [CompletableFuture]。这样,无需任何线程等待,就可以构造出操作链。这些方法由 [CompletionStage<T>] 接口声明,[CompletableFuture] 同样实现了该接口。

[CompletableFuture] 不是线程。它可能代表由执行器的线程执行的过程(如由 [supplyAsync] 创建的那些),但许多并不由任何线程执行:[Async01.java] 步骤 4 中的那个只是在一秒后由定时器“完成”,而 [HttpClient.sendAsync] 返回的那个则在服务器的响应到达时完成。它是对结果的一个承诺。

程序 [Async03.java] 演示了创建、查询和等待 [CompletableFuture] 的主要方式:

// CompletableFuture:创建、等待、状态、结果、后续处理
void main() throws InterruptedException {
    // 1 - supplyAsync 将一项处理交给执行器,并返回 CompletableFuture<T>
    CompletableFuture<Long> f1 = CompletableFuture.supplyAsync(() -> {
        // 几十分之一秒的计算
        long sum = 0;
        for (int i = 1; i <= 200_000_000; i++) {
            sum += i % 7;
        }
        return sum;
    });
    IO.println("f1 started, state: " + f1.state());
    // join() 等待处理结束,阻塞当前线程,并返回其结果
    long result = f1.join();
    IO.println("f1 finished, state: " + f1.state() + ", result: " + result);

    // 2 - 一个由定时器在 300 毫秒后完成的 CompletableFuture,不占用线程
    CompletableFuture<Void> f2 = new CompletableFuture<Void>()
            .completeOnTimeout(null, 300, TimeUnit.MILLISECONDS);
    IO.println("f2 started, state: " + f2.state());
    f2.join();
    IO.println("f2 finished, state: " + f2.state());

    // 3 - 已经完成的 CompletableFuture,成功或失败
    CompletableFuture<Integer> f3 = CompletableFuture.completedFuture(42);
    CompletableFuture<Integer> f4 = CompletableFuture.failedFuture(new IllegalStateException("failure"));
    IO.println("f3: state " + f3.state() + ", result " + f3.resultNow()
            + " ; f4: state " + f4.state() + ", exception " + f4.exceptionNow());

    // 4 - 失败的处理:join() 抛出包装其异常的 CompletionException
    CompletableFuture<Integer> f5 = CompletableFuture.supplyAsync(() -> Integer.parseInt("abc"));
    try {
        f5.join();
    } catch (CompletionException e) {
        IO.println("f5: state " + f5.state() + ", join() throws " + e.getClass().getSimpleName()
                + " containing " + e.getCause());
    }

    // 5 - 继承自 Future 接口的 get() 将异常包装在 ExecutionException 中
    try {
        f5.get();
    } catch (ExecutionException e) {
        IO.println("f5: get() throws " + e.getClass().getSimpleName()
                + " containing " + e.getCause().getClass().getSimpleName());
    }

    // 6 - 后续处理:CompletableFuture 完成时要做什么
    CompletableFuture<Integer> f6 = f2.thenApply(nothing -> 2 * 21);
    CompletableFuture<Void> f7 = f6.thenAccept(value -> IO.println("f7: the continuation received " + value));
    f7.join();

    // 7 - isDone、isCompletedExceptionally、isCancelled
    IO.println("f1: isDone=" + f1.isDone() + ", f5: isDone=" + f5.isDone()
            + ", isCompletedExceptionally=" + f5.isCompletedExceptionally()
            + ", isCancelled=" + f5.isCancelled());
}

结果:

> java Async03.java
f1 started, state: RUNNING
f1 finished, state: SUCCESS, result: 599999998
f2 started, state: RUNNING
f2 finished, state: SUCCESS
f3: state SUCCESS, result 42 ; f4: state FAILED, exception java.lang.IllegalStateException: failure
f5: state FAILED, join() throws CompletionException containing java.lang.NumberFormatException: For input string: "abc"
f5: get() throws ExecutionException containing NumberFormatException
f7: the continuation received 42
f1: isDone=true, f5: isDone=true, isCompletedExceptionally=true, isCancelled=false

说明:

  • 第 4–11 行:[CompletableFuture.supplyAsync(supplier)] 把一个无参数的函数([Supplier<T>])传给执行器,并立即返回表示其执行过程的 [CompletableFuture<T>]。该函数返回 [long],因此我们得到 [CompletableFuture<Long>]。如果没有显式指定执行器,则由 JVM 的公共池 [ForkJoinPool.commonPool()] 执行该函数;稍后我们会看到如何选择执行器。对于没有结果的处理操作([Runnable]),我们使用 [runAsync],它返回 [CompletableFuture<Void>];
  • 第 12 行:方法 [state()] (Java 19)返回操作的状态:[RUNNING] (进行中)、[SUCCESS] (成功完成)、[FAILED] (因异常而终止)或 [CANCELLED] (已取消)。这些是 [Future.State] 枚举的常量;后三个是最终状态:已完成的操作不再改变状态;
  • 第 14 行:[join()] 等待操作结束并返回其结果。与上一章的 [Thread.join] 一样,这是阻塞式等待:当前线程被挂起(这里是主线程,对小型控制台程序来说这不是问题);
  • 第 17–22 行:一个由其创建者创建为“进行中”、并在 300 毫秒后由定时器终结的 [CompletableFuture] ([completeOnTimeout],Java 9)。在此期间不占用任何线程:这相当于 [Thread.sleep(300)] 的异步版本。它的类型是 [CompletableFuture<Void>]:它不返回结果([Void] 是与 [void] 对应的类;其唯一的值是 [null]);
  • 第 25–28 行:[completedFuture(42)] 返回一个结果为 42、事先已完成的 [CompletableFuture],而 [failedFuture(exception)] (Java 9)返回一个已经失败的 [CompletableFuture]。当方法需要返回 *[CompletableFuture] 但已经拥有结果(例如缓存值)或已经知道它会失败时,就会用到它们。[resultNow()] 和 [exceptionNow()] (Java 19)无需等待即可返回已完成操作的结果或异常(如果操作不处于所需状态,它们会抛出 [IllegalStateException]* );
  • 第 31–37 行:函数抛出异常的操作以 [FAILED] 状态结束。异常存储在 [CompletableFuture] 中,[join()] 会触发一个 [CompletionException] (未受检异常),其原因([getCause()])是原始异常,这里是 [NumberFormatException];
  • 第 40–45 行:[get()],即从 [Future] 接口继承的方法,同样以阻塞状态等待,但会把异常包装在 [ExecutionException](一种受检异常)中,并且还可能抛出 [InterruptedException],它同样是受检异常:因此该调用被放在 *[try / catch] 中,由它拦截第一个异常,而 *[main] 方法声明了第二个异常(第 2 行)。在操作 [join()] 的代码中,使用 [CompletableFuture] 更方便;[get()] 是对简单的 [Future] 唯一可用的方法,并且有一个带延时的版本 [get(timeout, unit)];
  • 第 48–50 行:一个后续操作。[f2.thenApply(function)] 返回一个新的 [CompletableFuture],一旦 [f2] 完成,它就会用把函数应用于 [f2] 的结果所得的值来完成。这里,该函数忽略其参数([null])并返回 42:由此得到一个 [CompletableFuture<Integer>]。[thenAccept] 附加一个消费结果而不产生结果的函数([Consumer<T>]),并返回一个 [CompletableFuture<Void>]。如果原始操作失败,则不会执行后续操作,失败会沿着链传播;
  • 第 53–55 行:布尔方法 [isDone()] (已完成,无论以何种方式)、[isCompletedExceptionally()] (因异常而完成或已中止)和 [isCancelled()] (已中止)。

[CompletableFuture] 中有大量方法(超过五十个)。下表列出了我们将要使用的方法:

方法
作用
[supplyAsync(f)]、[runAsync(r)]
使用执行器执行一个函数(有结果或无结果)
[completedFuture(v)]、[failedFuture(e)]
创建一个已经完成的操作,无论成功还是失败
[complete(v)]、[completeExceptionally(e)]
自行完成一个任务
[thenApply(f)]
转换结果:[T → U]
[thenAccept(c)]、[thenRun(r)]
使用结果,或在操作之后执行一个动作
[thenCompose(f)]
链接另一个异步操作:[T → CompletableFuture<U>]
[thenCombine(other, f)]
合并两个并行执行的操作的结果
[allOf(...)]、[anyOf(...)]
等待所有操作完成,或等待第一个操作完成
[exceptionally(f)]、[handle(f)]、[whenComplete(c)]
处理或观察失败
[orTimeout(...)]、[completeOnTimeout(...)]
限制操作的持续时间
[join()]、[get()]
通过阻塞当前线程来等待结果

方法 [thenXxx]、[handle] 和 [whenComplete] 也存在 [thenXxxAsync] 版本:我们将在“由哪个线程执行其余代码?”一节中讨论其区别。

9.3. 异步方法

9.3.1. 第一种方法:返回 CompletableFuture

在 Java 中,异步方法就是一个发起操作并立即返回(不等待)一个表示该操作的 [CompletableFuture] 的方法:

  • 如果操作不返回结果,则返回 [CompletableFuture<Void>];
  • 如果操作返回类型为 [T] 的结果,则返回 [CompletableFuture<T>]。

语言没有强制任何命名约定。Java 库经常给这些方法加上后缀 [Async] ([sendAsync]、[supplyAsync]),但这并不是规则:返回类型就足以识别它们。

程序 [Async04.java] 煮咖啡并数方糖:

// 返回 CompletableFuture 的方法:各步骤通过 thenRun 和 thenCompose 组合
final long start = System.nanoTime();

void main() {
    display("call of makeCoffee");
    CompletableFuture<Void> preparation = makeCoffee();
    display("makeCoffee has returned: the program continues");
    display("call of countSugars");
    CompletableFuture<Integer> counting = countSugars(3);
    display("countSugars has returned");
    // 我们组合这两个操作,然后等待组合的结果
    int nbSugars = preparation.thenCombine(counting, (nothing, count) -> count).join();
    display("coffee ready, with " + nbSugars + " sugar(s)");
}

// 不返回结果的操作:它返回 CompletableFuture<Void>
CompletableFuture<Void> makeCoffee() {
    display("  coffee: the machine is heating up");
    // 该方法描述步骤序列,然后立即返回
    return delay(1000)
            .thenRun(() -> display("  coffee: the machine is pouring the coffee"))
            .thenCompose(nothing -> delay(500))
            .thenRun(() -> display("  coffee: done"));
}

// 返回整数的操作:它返回 CompletableFuture<Integer>
CompletableFuture<Integer> countSugars(int count) {
    // 以一个已完成的 CompletableFuture 开头的步骤链
    CompletableFuture<Void> steps = CompletableFuture.completedFuture(null);
    for (int i = 1; i <= count; i++) {
        // lambda 表达式只能使用实际上为 final 的局部变量
        int number = i;
        steps = steps.thenCompose(nothing -> delay(200))
                .thenRun(() -> display("  sugar no. " + number));
    }
    // 链的末端:结果,即糖的数量
    return steps.thenApply(nothing -> count);
}

// Thread.sleep 的异步等价物:在 [ms] 毫秒后完成的 CompletableFuture
CompletableFuture<Void> delay(long ms) {
    return new CompletableFuture<Void>().completeOnTimeout(null, ms, TimeUnit.MILLISECONDS);
}

// 显示自开始以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

结果:

> java Async04.java
    3 ms : call of makeCoffee
   12 ms :   coffee: the machine is heating up
   15 ms : makeCoffee has returned: the program continues
   16 ms : call of countSugars
   17 ms : countSugars has returned
  217 ms :   sugar no. 1
  417 ms :   sugar no. 2
  618 ms :   sugar no. 3
 1014 ms :   coffee: the machine is pouring the coffee
 1515 ms :   coffee: done
 1516 ms : coffee ready, with 3 sugar(s)

说明:

  • 第 40–43 行:[delay] 方法是 [Thread.sleep] 的异步等价物:它返回一个在超时之后完成的 [CompletableFuture<Void>] ,且不占用线程。我们将在许多示例中用它来模拟 I/O;
  • 第 17–24 行:一个没有结果的操作。该方法显示一条初始消息,然后描述各个步骤的顺序,并立即返回最终的 [CompletableFuture]:这就是为什么结果的第 4 行紧接在第 3 行之后出现,而不是在一秒半之后。这些步骤将在稍后执行,每一步都在前一步完成之后:
    • 第 21 行:[thenRun(action)] 在前一个操作完成时执行一个动作;
    • 第 22 行:[thenCompose(function)] 触发另一个异步操作:该函数本身返回一个 [CompletableFuture] (这里是一个新的 500 毫秒延迟),而 [CompletableFuture] (由 [thenCompose] 返回)要等到这第二个操作结束才会完成。如果使用 [thenApply],我们将得到一个 [CompletableFuture<CompletableFuture<Void>>],它会在第二个延迟刚一开始就完成:[thenCompose] 之于 [thenApply] ,就如同 [flatMap] 之于 [map] 在流 API 中的关系;
  • 第 27–38 行:一个返回整数的操作。循环无法在每次迭代时“等待”:它构建步骤序列,每次迭代都在现有序列上添加一个延迟和一次显示,起点是一个预先计算好的 [CompletableFuture] (第 29 行)。整条链在几微秒内构造完毕,然后随着各个延迟的发生而逐步展开。变量 [number] (第 32 行)是必需的,因为 lambda 只能使用实际上为 final 的局部变量,而 [i] 不是。最后,[thenApply] 把该字符串转换为 [CompletableFuture<Integer>],其结果是方糖的数量;
  • 第 6–10 行:主程序调用这两个方法。它获得两个 [CompletableFuture] 值并继续执行。这两个操作随后“同时”进行:在机器预热的同时数方糖(结果的第 7–9 行);
  • 第 12 行:[preparation.thenCombine(counting, function)] 在[CompletableFuture] 的两个操作都结束时返回一个已完成的结果,其值是把函数应用于这两个结果所得的值:这里保留的是方糖的数量。[join()] 等待这个结果。咖啡在 1.5 秒后就准备好了——即两个操作中较长者的持续时间——而不是 2.1 秒(1.5 + 3 × 0.2)之后。

我们可以看到这种方法的优点和局限。没有线程在等待:各个步骤随着时间间隔的流逝由定时器线程执行。但代码不再像一系列指令那样阅读:[countSugars] 循环并不做循环通常所做的事(它构造的是一条链,而不是执行迭代),而在这些步骤中间使用简单的 [if] 或 [try / catch] 就需要专门的方法。当语言不提供像 [await] 这样的关键字时,这就是你要付出的代价。

9.3.2. 第二种方法:虚拟线程上的阻塞代码

虚拟线程允许你把同样的方法写成普通的阻塞方法。程序 [Async05.java] 煮的是同一杯咖啡:

// 使用虚拟线程的同一杯咖啡:普通的阻塞方法,自上而下阅读
final long start = System.nanoTime();

void main() throws InterruptedException, ExecutionException {
    // 为交给它的每个任务创建一个虚拟线程的执行器
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        display("start of makeCoffee");
        Future<?> preparation = executor.submit(this::makeCoffee);
        display("makeCoffee is started: the program continues");
        display("start of countSugars");
        Future<Integer> counting = executor.submit(() -> countSugars(3));
        display("countSugars is started");
        // 现在我们等待这两个结果
        preparation.get();
        int nbSugars = counting.get();
        display("coffee ready, with " + nbSugars + " sugar(s)");
    }
}

// 不返回结果的普通方法
void makeCoffee() {
    display("  coffee: the machine is heating up");
    // 阻塞等待:在虚拟线程上,它会释放载体线程
    sleep(1000);
    display("  coffee: the machine is pouring the coffee");
    sleep(500);
    display("  coffee: done");
}

// 返回整数的普通方法
int countSugars(int count) {
    for (int i = 1; i <= count; i++) {
        sleep(200);
        display("  sugar no. " + i);
    }
    return count;
}

// 没有受检异常的 Thread.sleep:中断会变成 CancellationException
void sleep(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        // 抛出异常之前,我们恢复线程的中断标志
        Thread.currentThread().interrupt();
        throw new CancellationException("wait interrupted");
    }
}

// 显示自开始以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

结果:

> java Async05.java
    3 ms : start of makeCoffee
   17 ms :   coffee: the machine is heating up
   18 ms : makeCoffee is started: the program continues
   18 ms : start of countSugars
   19 ms : countSugars is started
  221 ms :   sugar no. 1
  422 ms :   sugar no. 2
  623 ms :   sugar no. 3
 1020 ms :   coffee: the machine is pouring the coffee
 1521 ms :   coffee: done
 1522 ms : coffee ready, with 3 sugar(s)

说明:

  • 第 20–37 行:这两个操作都是普通方法:[makeCoffee] 不返回任何内容([void]),而 [countSugars] 返回 [int]。这些调用是阻塞的 [Thread.sleep] 操作;循环是真正的循环。这些方法中没有任何迹象表明它们将被并发执行:它们完全可以被直接调用;
  • 第 39–48 行:方法 [sleep] 调用 [Thread.sleep] ,并在重置线程的中断标志之后,把任何 [InterruptedException] (受检异常)转换为一个 [CancellationException] (非受检异常):这是在拦截 [InterruptedException] 而不传播它时应遵守的规则(我们将在取消一节中回到这一点);
  • 第 6 行:一个为每个任务创建一个虚拟线程的执行器。它在带资源的 [try] 中声明:其 [close()] 方法会等待所有任务完成;
  • 第 8 行和第 11 行:[submit] 把每个方法委托给一个新的虚拟线程,并返回一个 [Future]。方法引用 [this::makeCoffee] 是一个 [Runnable] (该方法不返回任何内容),得到一个 [Future<?>];lambda [() -> countSugars(3)] 是一个 [Callable<Integer>],得到一个 [Future<Integer>];
  • 第 14–15 行:主程序使用 [get()] 等待两个结果。这是主线程的阻塞式等待,在这里没有任何影响;
  • 结果与 [Async04.java] 相同:总共 1.5 秒,在机器预热的同时数完方糖。在等待期间,没有系统线程被阻塞:两个虚拟线程都已从各自的载体线程上分离。

使用虚拟线程时,异步不再是代码编写的问题,而是执行的问题:我们编写阻塞代码,而等待是否会阻塞系统线程,取决于执行器的选择(虚拟线程而不是平台线程池)。这就是为什么现有的 Java 库(JDBC、文件、套接字、[HttpClient.send]……)都是以阻塞方式编写的,却无需修改就能受益于虚拟线程。

9.3.3. JVM 做了什么

虚拟线程如何能在循环中途被中断、释放其宿主线程,随后又在同一位置恢复执行,并保持相同的局部变量值,甚至可能是在另一个宿主线程上?虚拟线程是一个 Java 对象([java.lang.VirtualThread],派生自 [Thread] 的类),它拥有自己的调用栈。为了执行它,JVM 把它“挂载”到一个载体线程上——这是专为此目的保留的 [ForkJoinPool] 中的平台线程,默认情况下该线程池的线程数与处理器数相同。当虚拟线程调用阻塞操作时([Thread.sleep],从套接字读取;[BlockingQueue.take],等待锁……),JVM 中的相关类(在 Java 21 中为此而重写)不会阻塞所在的线程:

  • 它们向系统注册该操作(延迟使用定时器,套接字使用系统的 I/O 通知机制——在 Linux 上是 [epoll] );
  • 它们“卸载”虚拟线程:其调用栈帧被复制到堆上,成为一个称为延续(continuation)的对象,而载体线程被归还给 [ForkJoinPool],由它为该线程分配另一个就绪的虚拟线程;
  • 当操作完成时,虚拟线程再次就绪:它将被重新挂载到第一个可用的载体线程上,其栈帧被重新复制,并在阻塞调用之后立即恢复执行。

这正是回调方法(“操作完成时回调我”)背后的原理,但分解执行、保存变量以及在调用栈层面恢复上下文的是 JVM,源代码中看不到任何痕迹。其他语言把这项任务交给编译器,由编译器把每个 [async] 方法转换成一个“状态机”;Java 则把它交给 JVM,这使得它能够以同样的方式处理所有现有代码。

有两个局限需要注意:

  • 某些操作无法使虚拟线程分离;它因此仍然“固定”在其宿主线程上,该宿主线程在等待期间被阻塞。这种情况发生在执行本地方法期间,以及大多数文件读写期间(系统没有提供可供 JVM 使用的文件通知机制);对于后者,[ForkJoinPool] 会通过临时创建一个额外的载体线程来进行补偿。直到 Java 23,在 [synchronized] 块内等待的虚拟线程也是如此;从 Java 24 起,情况不再如此;
  • 虚拟线程不会加快计算:执行计算的虚拟线程在整个计算期间都占用其宿主线程。虚拟线程适用于大量等待的程序,而不是大量计算的程序(对于后者,可以使用上一章的线程池和并行流)。

9.3.4. 由哪个线程执行后续部分?

程序 [Async06.java] 显示执行每段代码的线程:

// 处理的其余部分由哪个线程执行?
void main() throws InterruptedException {
    display("start of the program, parallelism of the common pool: " + ForkJoinPool.getCommonPoolParallelism());

    // 1 - 已完成的 CompletableFuture 的后续处理由调用者立即执行
    CompletableFuture.completedFuture(42).thenAccept(value -> display("1 - thenAccept, result known"));

    // 2 - 否则,由完成该 CompletableFuture 的线程执行
    delay(100).thenRun(() -> display("2 - thenRun after a delay")).join();
    CompletableFuture<String> order = new CompletableFuture<>();
    order.thenAccept(text -> display("2 - thenAccept after complete(\"" + text + "\")"));
    Thread.ofPlatform().name("deliverer").start(() -> order.complete("delivered")).join();

    // 3 - xxxAsync 变体将后续处理交给执行器
    delay(100).thenRunAsync(() -> display("3 - thenRunAsync, default executor")).join();
    ThreadFactory factory = Thread.ofPlatform().name("pool-", 1).factory();
    try (ExecutorService pool = Executors.newFixedThreadPool(2, factory)) {
        delay(100).thenRunAsync(() -> display("3 - thenRunAsync, chosen executor"), pool).join();
        CompletableFuture.runAsync(() -> display("3 - runAsync, chosen executor"), pool).join();
    }
    try (ExecutorService virtuals = Executors.newVirtualThreadPerTaskExecutor()) {
        CompletableFuture.runAsync(() -> display("3 - runAsync, virtual threads"), virtuals).join();
    }

    // 4 - 虚拟线程在每次等待之后都可能更换载体线程
    Thread a = Thread.ofVirtual().start(() -> work("A"));
    Thread b = Thread.ofVirtual().start(() -> work("B"));
    a.join();
    b.join();
    display("end of the program");
}

void work(String name) {
    for (int i = 1; i <= 3; i++) {
        display("  " + name + i + " : before the wait");
        sleep(100);
    }
}

// 在 [ms] 毫秒后完成的 CompletableFuture
CompletableFuture<Void> delay(long ms) {
    return new CompletableFuture<Void>().completeOnTimeout(null, ms, TimeUnit.MILLISECONDS);
}

// 没有受检异常的 Thread.sleep:中断会变成 CancellationException
void sleep(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new CancellationException("wait interrupted");
    }
}

// 以执行显示的线程为前缀的显示
// (平台线程的名称,虚拟线程的描述)
void display(String message) {
    Thread thread = Thread.currentThread();
    IO.println("[" + (thread.isVirtual() ? thread.toString() : thread.getName()) + "] " + message);
}

结果:

> java Async06.java
[main] start of the program, parallelism of the common pool: 1
[main] 1 - thenAccept, result known
[ForkJoinPool.commonPool-delayScheduler] 2 - thenRun after a delay
[deliverer] 2 - thenAccept after complete("delivered")
[ForkJoinPool.commonPool-worker-1] 3 - thenRunAsync, default executor
[pool-1] 3 - thenRunAsync, chosen executor
[pool-2] 3 - runAsync, chosen executor
[VirtualThread[#28]/runnable@ForkJoinPool-1-worker-1] 3 - runAsync, virtual threads
[VirtualThread[#31]/runnable@ForkJoinPool-1-worker-1]   A1 : before the wait
[VirtualThread[#32]/runnable@ForkJoinPool-1-worker-2]   B1 : before the wait
[VirtualThread[#32]/runnable@ForkJoinPool-1-worker-2]   B2 : before the wait
[VirtualThread[#31]/runnable@ForkJoinPool-1-worker-1]   A2 : before the wait
[VirtualThread[#31]/runnable@ForkJoinPool-1-worker-2]   A3 : before the wait
[VirtualThread[#32]/runnable@ForkJoinPool-1-worker-1]   B3 : before the wait
[main] end of the program

说明:

  • 第 3 行:共享池([ForkJoinPool.commonPool()])是 [CompletableFuture] 的默认执行器,其并行度等于处理器数减一,在我们这台 2 处理器的机器上为 1(结果的第 2 行);
  • 第 6 行:已完成的 [CompletableFuture] 的 后续操作由附加它的线程立即执行:线程 [main] (第 3 行);
  • 第 9–12 行:如果操作尚未完成,后续操作将由完成它的线程执行:对于 [delay(100)] 是超时定时器线程(第 4 行),对于订单则是线程 [deliverer],它调用 [complete](第 5 行)。因此,执行非异步后续操作的线程是无法选择的;对于简短的动作这无关紧要,但冗长或阻塞的后续操作会使该线程无法做其他事(例如定时器线程,它负责处理所有 [CompletableFuture] 的超时);
  • 第 15–23 行:[xxxAsync] 变体([thenRunAsync]、[thenApplyAsync]……)把后续操作委托给执行器:没有额外参数时委托给共享池(结果的第 6 行);如果最后一个参数是执行器,则委托给该执行器。这样就可以选择平台线程(第 7–8 行:一个两线程的线程池,其线程名由线程工厂 [ThreadFactory] 确定,该工厂由 [Thread.ofPlatform().name("pool-", 1).factory()] 构造),或者虚拟线程(第 9 行)。[supplyAsync] 和 [runAsync] 也接受执行器;
  • 第 26–38 行:两个虚拟线程,各自显示一条消息然后休眠,连续三次。结果表明它们并不始终附着在单个宿主线程上:31 号虚拟线程(A)从 [worker-1] 开始,到 [worker-2] 结束,而 32 号(B)则相反。当其中一个在休眠时,它的载体线程可供另一个使用。因此,在虚拟线程中,绝不能假定等待之后的代码与之前的代码由同一个载体线程执行;但它始终是同一个虚拟线程,而这才是程序所关心的([Thread.currentThread()] 返回的是虚拟线程;它的变量和 [ThreadLocal] 都得以保留)。

这种在不增加系统线程数的情况下同时执行多个操作的方式称为并发。它不同于并行,后者是在多个处理器上同时执行多个计算(如上一章所讨论的:线程池、并行流)。异步有助于 I/O 并发;它并不会让计算更快。

因此,执行器的选择很重要:

  • 共享池适用于简短的后续操作和短时间的计算;不应在其中执行阻塞操作,否则有 [Async01.java] 中所述的饥饿风险(在我们的机器上它只有一个线程);
  • 对于阻塞操作(I/O、对 JDBC 或 [Thread.sleep] 的调用),请使用虚拟线程执行器:[CompletableFuture.supplyAsync(supplier, virtualExecutor)];
  • 对于图形用户界面,我们传入一个让 UI 线程执行后续操作的执行器,这样就可以更新图形组件:在 Swing 中使用 [thenAcceptAsync(action, SwingUtilities::invokeLater)](方法引用 [SwingUtilities::invokeLater] 是一个有效的 [Executor],因为 [Executor] 是一个函数式接口,其唯一的方法接受一个 [Runnable]);在 JavaFX 中使用 [Platform::runLater]。

9.3.5. 主程序

在其他语言中,异步程序的 main 方法必须以特定的方式声明。在 Java 中没有这样的要求:方法 [main] 由平台线程 [main] 执行,由该方法负责等待它发起的操作完成——使用 [join()] 或 [get()]。这是唯一一个对 [CompletableFuture] 进行阻塞等待属于正常做法的地方。[Async07.java] 程序执行一个异步倒计时:

// 主程序等待异步操作结束并设置退出码
void main(String[] args) {
    // 秒数作为参数传入
    if (args.length != 1 || !args[0].matches("\\d+")) {
        IO.println("syntax: java Async07.java nbSeconds");
        // 程序的退出码:0 表示成功,其他值表示错误
        System.exit(1);
    }
    CompletableFuture<Void> countdown = countDown(Integer.parseInt(args[0]));
    IO.println("countdown started");
    // 没有这个等待,main 会立即结束,程序也随之结束
    countdown.join();
    IO.println("finished");
}

// 异步循环用递归编写:每一步启动下一步
CompletableFuture<Void> countDown(int nbSeconds) {
    if (nbSeconds == 0) {
        return CompletableFuture.completedFuture(null);
    }
    IO.println("still " + nbSeconds + " s");
    return delay(1000).thenCompose(nothing -> countDown(nbSeconds - 1));
}

// 在 [ms] 毫秒后完成的 CompletableFuture
CompletableFuture<Void> delay(long ms) {
    return new CompletableFuture<Void>().completeOnTimeout(null, ms, TimeUnit.MILLISECONDS);
}

结果,先是带参数,然后是不带参数:

1
2
3
4
5
6
> java Async07.java 3
still 3 s
countdown started
still 2 s
still 1 s
finished
1
2
3
4
> java Async07.java
syntax: java Async07.java nbSeconds
> echo $?
1

说明:

  • 第 2 行:[main] 的 [args] 参数接收命令行参数,这些参数放在文件名之后:[java Async07.java 3];
  • 第 4–8 行:如果缺少参数,或者参数不是正整数(正则表达式 [\d+]:一个或多个数字),程序就用 [System.exit(1)] 终止。传给 [System.exit] 的整数是程序的退出码(0 表示成功,任何其他值表示错误),脚本可以检查它:在 Linux 上用 [echo $?] (第二个结果),在 Windows 上用 [echo %ERRORLEVEL%]。[main] 方法正常结束的程序返回代码 0;
  • 第 16–23 行:一个异步倒计时。异步循环自然地通过递归来实现:每一步先显示一条消息,然后使用 [thenCompose] 引入一秒的延迟,再接着执行下一步。这里没有调用栈:递归调用是一秒后通过后续操作进行的;
  • 第 9–12 行:方法 [countDown] 显示它的第一条消息,然后交还控制权(结果的第 2–3 行);主程序用 [join()] 等待操作结束。如果没有这个等待,[main] 会立即结束,程序也随之结束:当只剩下守护线程 时,JVM 就会停止,而定时器线程和共享池线程都是守护线程。虚拟线程也是如此,它们始终是守护线程:程序必须等待自己启动的虚拟线程结束(使用 [join]、[get] 或其执行器的 [close] 方法)。

9.4. 顺序执行与并发执行

9.4.1. allOf 和 invokeAll

煮咖啡的例子已经说明了这一点:异步操作发起的时刻和它被等待的时刻可以不同。写成 [method().join()] 会发起操作并立即等待它;而写成 [var f = method();] ,之后再写 [f.join();] ,则允许在两者之间启动其他操作。程序 [Async08.java] 用耗时一秒的操作比较这两种方法:

// 一秒钟操作的顺序执行与并发执行
long start = System.nanoTime();

void main() throws InterruptedException {
    // 1 - 顺序:等待每个操作结束后再启动下一个
    int a = readTemperature("Angers").join();
    int b = readTemperature("Brest").join();
    int c = readTemperature("Colmar").join();
    IO.println("in sequence: " + a + ", " + b + ", " + c + " in " + elapsed() + " ms");

    // 2 - 并发:我们启动三个操作,然后等待它们
    start = System.nanoTime();
    CompletableFuture<Integer> fa = readTemperature("Angers");
    CompletableFuture<Integer> fb = readTemperature("Brest");
    CompletableFuture<Integer> fc = readTemperature("Colmar");
    CompletableFuture.allOf(fa, fb, fc).join();
    IO.println("concurrently: " + fa.resultNow() + ", " + fb.resultNow() + ", " + fc.resultNow()
            + " in " + elapsed() + " ms");

    // 3 - 对 CompletableFuture 列表使用 allOf,然后得到结果列表
    start = System.nanoTime();
    List<String> cities = List.of("Angers", "Brest", "Colmar", "Dijon", "Évry", "Foix");
    List<CompletableFuture<Integer>> readings = cities.stream().map(this::readTemperature).toList();
    List<Integer> temperatures = CompletableFuture.allOf(readings.toArray(CompletableFuture[]::new))
            .thenApply(nothing -> readings.stream().map(CompletableFuture::join).toList())
            .join();
    IO.println(cities.size() + " cities: " + temperatures + " in " + elapsed() + " ms");

    // 4 - 用虚拟线程和阻塞方法实现同样的事情
    start = System.nanoTime();
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        List<Callable<Integer>> tasks = cities.stream()
                .map(city -> (Callable<Integer>) () -> readTemperatureBlocking(city))
                .toList();
        // invokeAll 启动所有任务,并在它们全部结束后返回它们的 Future
        List<Integer> results = executor.invokeAll(tasks).stream().map(Future::resultNow).toList();
        IO.println(cities.size() + " cities (virtual threads): " + results + " in " + elapsed() + " ms");
    }
}

// 模拟查询一个一秒后回答的远程服务
CompletableFuture<Integer> readTemperature(String city) {
    // 由城市名称派生的“温度”
    return delay(1000).thenApply(nothing -> 10 + city.length());
}

// 同样的操作,以阻塞方式编写
int readTemperatureBlocking(String city) throws InterruptedException {
    Thread.sleep(1000);
    return 10 + city.length();
}

// 在 [ms] 毫秒后完成的 CompletableFuture
CompletableFuture<Void> delay(long ms) {
    return new CompletableFuture<Void>().completeOnTimeout(null, ms, TimeUnit.MILLISECONDS);
}

// 自 [start] 起经过的毫秒数
long elapsed() {
    return (System.nanoTime() - start) / 1_000_000;
}

结果:

1
2
3
4
5
> java Async08.java
in sequence: 16, 15, 16 in 3007 ms
concurrently: 16, 15, 16 in 1000 ms
6 cities: [16, 15, 16, 15, 14, 14] in 1006 ms
6 cities (virtual threads): [16, 15, 16, 15, 14, 14] in 1013 ms

说明:

  • 第 41–45 行:模拟的操作:一秒的延迟,然后得到一个由城市名长度推导出的“温度”;
  • 第 6–8 行:每个操作都是先启动,再等待它完成,然后才启动下一个。三个操作一个接一个地执行:3 秒(结果的第 2 行)。当一个操作需要上一个操作的结果时,这是正确的做法(此时应改为编写 [thenCompose] 链);
  • 第 13–15 行:三个操作启动时互不等待。它们同时运行;
  • 第 16 行:[CompletableFuture.allOf(...)] 返回一个 [CompletableFuture<Void>],它在传给它的所有操作都结束时完成。我们用 [join()] 等待它:1 秒而不是 3 秒(第 3 行);
  • 第 17–18 行:这三个操作都已完成,因此 [resultNow()] 立即返回它们的结果;
  • 第 22–27 行:操作列表的情形。[allOf] 等待一个数组([CompletableFuture<?>...]):由列表的 [toArray(CompletableFuture[]::new)] 方法创建它。[allOf] 不返回结果:结果是在一个后续操作中通过对每个操作调用 [join()] 收集的,由于它们都已完成,所以不会阻塞。结果列表按操作的顺序(而不是它们完成的顺序)得到。表达式 [cities.stream().map(this::readTemperature).toList()] 对每个城市调用该方法,从而同时启动六个操作;这六个操作合计耗时一秒(第 4 行);
  • 第 29–38 行:用由虚拟线程执行的阻塞方法(第 47–51 行)做同样的事。执行器的 [invokeAll] 方法接收一个 [Callable<T>] 集合,启动它们全部,并在它们都完成时返回它们的 [Future<T>] 列表:这是 *[allOf] 的阻塞式等价物。第 33 行的类型转换 [(Callable<Integer>)] 告诉编译器 lambda 的类型,而编译器在 [map]* 中无法自行推断出它。六个操作合计耗时一秒(第 5 行)。

9.4.2. anyOf

[CompletableFuture.anyOf(...)] 返回一个 [CompletableFuture<Object>] ,只要传给它的操作中有一个完成,它就会终止,其结果(或异常)就是该操作的结果(或异常)。程序 [Async09.java] 以两种方式使用它:

// anyOf:对第一个完成的操作作出反应
long start = System.nanoTime();

void main() {
    // 1 - 我们查询三个镜像服务器,保留第一个回答
    List<CompletableFuture<String>> requests = List.of(
            query("mirror-paris", 800),
            query("mirror-lyon", 300),
            query("mirror-lille", 600));
    // anyOf 返回 CompletableFuture<Object>,其完成方式与第一个完成的操作相同
    Object first = CompletableFuture.anyOf(requests.toArray(CompletableFuture[]::new)).join();
    display("first answer: " + first);
    // 其他请求继续进行:我们在这里等待它们,以便看到它们的回答
    CompletableFuture.allOf(requests.toArray(CompletableFuture[]::new)).join();
    display("all the answers: " + requests.stream().map(CompletableFuture::resultNow).toList());

    // 2 - 限时操作:我们让它与延时“竞速”
    start = System.nanoTime();
    CompletableFuture<String> slow = query("slow-server", 2000);
    CompletableFuture<Object> race = CompletableFuture.anyOf(slow, delay(500));
    race.join();
    if (slow.isDone()) {
        display("answer obtained in time: " + slow.join());
    } else {
        display("the slow server did not answer within the 500 ms delay");
    }
}

// 模拟一个在 [duration] 毫秒后回答的服务器
CompletableFuture<String> query(String server, int duration) {
    return delay(duration).thenApply(nothing -> server + " (" + duration + " ms)");
}

// 在 [ms] 毫秒后完成的 CompletableFuture
CompletableFuture<Void> delay(long ms) {
    return new CompletableFuture<Void>().completeOnTimeout(null, ms, TimeUnit.MILLISECONDS);
}

// 显示自 [start] 以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

结果:

1
2
3
4
> java Async09.java
  309 ms : first answer: mirror-lyon (300 ms)
  806 ms : all the answers: [mirror-paris (800 ms), mirror-lyon (300 ms), mirror-lille (600 ms)]
  500 ms : the slow server did not answer within the 500 ms delay

说明:

  • 第 6–9 行:查询三个镜像服务器;它们都持有相同的信息,但响应速度不同。这三个操作存储在一个列表中;
  • 第 11 行:[anyOf] 返回一个 [CompletableFuture<Object>],其结果是第一个完成的操作的结果。它的类型是 [Object] ,因为传给 [anyOf] 的操作可能具有不同的结果类型:要把它当作字符串使用,就需要进行类型转换。第一个响应在 300 毫秒后到达(结果的第 2 行);
  • 第 14 行:其他请求不会被 [anyOf] 终止;它们会继续运行直到结束。这里,我们等待它们显示出所有响应(第 3 行);
  • 第 19–26 行:[anyOf] 的一个常见用法:通过让操作与超时进行一场“竞赛”来限制等待的时长。如果竞赛结束时操作尚未完成,说明超时获胜:操作耗时过长(第 4 行)。[CompletableFuture] 提供了一种更直接的方式来编写这种情形,即 [orTimeout] 方法,稍后介绍。

9.4.3. 边完成边处理结果

我们常常希望在多个操作完成时就处理其结果,而不必等待最慢的那个。使用 [CompletableFuture] 时,这很简单:只需为每个操作附加一个后续操作。对于提交给执行器的任务,[ExecutorCompletionService] 类(Java 5)按任务完成的顺序返回 [Future] 对象。程序 [Async10.java] 以这两种方式处理五个“文件”,每个文件的处理耗时在 100 到 900 毫秒之间:

// 按操作完成的顺序处理结果
long start = System.nanoTime();
final int[] durations = {900, 300, 700, 100, 500};

void main() throws InterruptedException, ExecutionException {
    // 1 - 使用 CompletableFuture:每个操作一个后续处理,一结束就执行
    List<CompletableFuture<Void>> displays = new ArrayList<>();
    for (int i = 0; i < durations.length; i++) {
        displays.add(process("file" + i + ".txt", durations[i]).thenAccept(this::display));
    }
    CompletableFuture.allOf(displays.toArray(CompletableFuture[]::new)).join();
    display("1 - all the files have been processed");

    // 2 - 使用虚拟线程:CompletionService 按完成的顺序交付 Future
    start = System.nanoTime();
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        CompletionService<String> service = new ExecutorCompletionService<>(executor);
        for (int i = 0; i < durations.length; i++) {
            String file = "file" + i + ".txt";
            int duration = durations[i];
            service.submit(() -> processBlocking(file, duration));
        }
        // take() 等待(阻塞)下一个完成的任务
        for (int i = 0; i < durations.length; i++) {
            display(service.take().get());
        }
    }
    display("2 - all the files have been processed");
}

// 模拟耗时 [duration] 毫秒的文件处理
CompletableFuture<String> process(String file, int duration) {
    return new CompletableFuture<String>()
            .completeOnTimeout(file + " processed in " + duration + " ms", duration, TimeUnit.MILLISECONDS);
}

// 同样的处理,以阻塞方式编写
String processBlocking(String file, int duration) throws InterruptedException {
    Thread.sleep(duration);
    return file + " processed in " + duration + " ms";
}

// 显示自 [start] 以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

结果:

> java Async10.java
  107 ms : file3.txt processed in 100 ms
  318 ms : file1.txt processed in 300 ms
  508 ms : file4.txt processed in 500 ms
  707 ms : file2.txt processed in 700 ms
  906 ms : file0.txt processed in 900 ms
  907 ms : 1 - all the files have been processed
  115 ms : file3.txt processed in 100 ms
  314 ms : file1.txt processed in 300 ms
  514 ms : file4.txt processed in 500 ms
  714 ms : file2.txt processed in 700 ms
  914 ms : file0.txt processed in 900 ms
  915 ms : 2 - all the files have been processed

说明:

  • 第 7–11 行:每个处理任务都有自己的后续操作 [thenAccept(this::display)],一旦它结束就会执行:文件 3(100 毫秒)最先显示,文件 0(900 毫秒)最后显示(结果的第 2–6 行)。方法 [process] (第 31–35 行)在指定时长之后返回一个带有所需消息的已完成 [CompletableFuture<String>] ([completeOnTimeout] 直接接收结果值)。后续操作列表用来通过 [allOf] 等待所有显示完成;
  • 第 16–27 行:[CompletionService<T>] 包装一个执行器(这里是虚拟线程执行器)。其方法 [submit] 启动一个任务;其方法 [take()] 阻塞等待下一个已完成的任务,并返回它的 [Future],其结果随即由 [get()] 返回。因此,第 24–26 行的循环按文件完成的顺序处理它们(第 8–12 行);
  • 在这两种情况下,整个过程都耗时 900 毫秒——即最长处理步骤的时长——并且每个结果都会尽快显示。

9.5. 异步代码中的异常

9.5.1. 传播、exceptionally、handle、whenComplete

异步操作抛出的异常不会被抛回给发起该操作的代码:它被存储在 [CompletableFuture] 中,后者转入 [FAILED] 状态。然后它沿着后续操作链传播,直到遇到处理它的方法,或直到遇到 [join()],后者把它包装在 [CompletionException] 中重新抛出。程序 [Async11.java] 检查各种情形:

// 异步代码中的异常
void main() {
    // 1 - join() 抛出包装该操作异常的 CompletionException
    try {
        int value = readValue("twelve").join();
        IO.println("value = " + value);
    } catch (CompletionException e) {
        IO.println("1 - join() throws " + name(e) + ", with cause " + name(e.getCause())
                + " : " + e.getCause().getMessage());
    }

    // 2 - exceptionally 在失败时提供替代值
    int value = readValue("thirteen").exceptionally(e -> -1).join();
    IO.println("2 - exceptionally: replacement value " + value);

    // 3 - handle 接收结果或异常;whenComplete 观察它们而不做任何更改
    for (String text : List.of("14", "fifteen")) {
        String outcome = readValue(text)
                .whenComplete((v, e) -> IO.println("3 - whenComplete saw: " + (e == null ? v : name(e))))
                .handle((v, e) -> e == null ? "value " + v : "failure, " + name(cause(e)))
                .join();
        IO.println("3 - handle returned: " + outcome);
    }

    // 4 - 返回 CompletableFuture 的方法也可以在调用时立即抛出异常
    try {
        readValue(" ");
        IO.println("4 - the call threw nothing");
    } catch (IllegalArgumentException e) {
        IO.println("4 - it is the call itself that throws " + name(e) + " : " + e.getMessage());
    }

    // 5 - 对多个失败的操作使用 allOf
    List<CompletableFuture<Integer>> readings = Stream.of("1", "two", "3", "four")
            .map(this::readValue)
            .toList();
    try {
        CompletableFuture.allOf(readings.toArray(CompletableFuture[]::new)).join();
    } catch (CompletionException e) {
        // join() 只重新抛出其中一个异常……
        IO.println("5 - allOf fails with " + name(e.getCause()) + " : " + e.getCause().getMessage());
        // ……但每个操作都保留了自己的异常或结果
        for (CompletableFuture<Integer> reading : readings) {
            switch (reading.state()) {
                case SUCCESS -> IO.println("      success, result = " + reading.resultNow());
                case FAILED -> IO.println("      failure, " + name(reading.exceptionNow())
                        + " : " + reading.exceptionNow().getMessage());
                default -> IO.println("      unexpected state: " + reading.state());
            }
        }
    }
}

// 如果字符串不是整数则失败的异步操作
CompletableFuture<Integer> readValue(String text) {
    // 在启动操作之前立即检查参数
    if (text == null || text.isBlank()) {
        throw new IllegalArgumentException("the text must not be empty");
    }
    // 读取需要一点时间
    return new CompletableFuture<Void>()
            .completeOnTimeout(null, 100, TimeUnit.MILLISECONDS)
            .thenApply(nothing -> Integer.parseInt(text));
}

// 后续处理常常收到 CompletionException:我们回溯到它的原因
Throwable cause(Throwable e) {
    return e instanceof CompletionException && e.getCause() != null ? e.getCause() : e;
}

// 异常所属类的简单名称
String name(Throwable e) {
    return e.getClass().getSimpleName();
}

结果:

> java Async11.java
1 - join() throws CompletionException, with cause NumberFormatException : For input string: "twelve"
2 - exceptionally: replacement value -1
3 - whenComplete saw: 14
3 - handle returned: value 14
3 - whenComplete saw: CompletionException
3 - handle returned: failure, NumberFormatException
4 - it is the call itself that throws IllegalArgumentException : the text must not be empty
5 - allOf fails with NumberFormatException : For input string: "two"
      success, result = 1
      failure, NumberFormatException : For input string: "two"
      success, result = 3
      failure, NumberFormatException : For input string: "four"

说明:

  • 第 54–64 行:被测试的方法。它首先检查其参数,如果字符串为 [null] 或空,就抛出 [IllegalArgumentException]。否则,它返回一个等待 100 毫秒、然后转换整个字符串的操作,如果字符串不是数字,就会抛出 [NumberFormatException] ;
  • 第 4–10 行:标准情形。第 63 行的后续操作中 [Integer.parseInt] 抛出的异常被 [CompletableFuture] 捕获;[join()] 把该异常包装在 [CompletionException] 中重新抛出,[getCause()] 可以从中取回原始异常(结果的第 2 行);
  • 第 13 行:[exceptionally(function)] 返回一个 [CompletableFuture] ,如果操作成功,它的结果与操作相同,否则其结果是把函数应用于该异常所得的结果:这就是 [catch] 在 [CompletableFuture] 世界中的对应物。这里,失败被替换为值 -1(第 3 行);
  • 第 17–23 行:另外两个方法,先应用于成功的操作,再应用于失败的操作:
    • [whenComplete(action)] 接收结果和异常(两者之一为 [null]),并且不改变任何东西:它返回的 [CompletableFuture] 与该操作具有相同的结果或相同的异常。它用于观察(记录日志、释放资源):这就是 [finally] 在 [CompletableFuture] 世界中的对应物;
    • [handle(function)] 同样接收结果和异常,并在两种情况下都返回一个新值:它把成功和失败都转换为一个结果;
    • 结果的第 6 行和第 7 行揭示了一个陷阱:后续操作收到的异常不是 [NumberFormatException] ,而是包装了它的 [CompletionException],因为失败发生在链的前一步(第 63 行的后续操作)。方法 [cause] (第 66–69 行)会回溯到原始异常:我们要养成把它写出来的习惯;
  • 第 26–31 行:与其他语言中的 [async] 方法的一个重要区别:返回 [CompletableFuture] 的方法是普通方法,它可以在被调用时立即抛出异常,即在创建任何 [CompletableFuture] 之前。这里空字符串就是这种情况(结果的第 8 行)。因此,调用代码必须同时预期这两类错误,或者该方法必须返回一个已经失败的操作([return CompletableFuture.failedFuture(new IllegalArgumentException(...));]),这通常更可取;
  • 第 34–38 行:我们用 [allOf] 等待四个操作,其中两个失败。[allOf] 返回的 [CompletableFuture] 随之失败,但只带有其中一个异常(结果的第 9 行);
  • 第 43–50 行:每个操作都保留了它的结果或异常。我们使用 [switch] 检查它们的状态;[exceptionNow()] 返回原始异常,不带包装。[allOf] 的失败并不妨碍其他操作成功(第 10 行和第 12 行)。

使用虚拟线程时,这个问题不会以同样的方式出现:虚拟线程执行的是普通代码,其中异常照常传播,并由 [try / catch] 拦截。只有两个线程之间的边界需要特别注意:提交给执行器的任务的异常存储在它的 [Future] 中,而 [get()] 会把它包装在 [ExecutionException] 中重新抛出。

9.5.2. 被遗忘的操作

对于没有人等待的操作,它的异常会怎样?程序 [Async12.java] 演示了这一点:

// 启动后被遗忘的操作:它的异常丢失了
void main() {
    // 处理线程中没有任何代码捕获的异常的处理程序
    Thread.setDefaultUncaughtExceptionHandler((thread, e) ->
            IO.println("uncaught exception in [" + thread.getName() + "] : " + e.getMessage()));

    // 1 - 被等待的 CompletableFuture:它的异常被捕获
    try {
        save("a").join();
    } catch (CompletionException e) {
        IO.println("1 - awaited CompletableFuture: exception caught: " + e.getCause().getMessage());
    }

    // 2 - 被遗忘的 CompletableFuture:它的异常留在对象中,没有人会看到
    save("b");
    IO.println("2 - forgotten CompletableFuture: the call has returned");

    // 3 - 提交给执行器后被遗忘的任务:它的异常留在 Future 中
    ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
    executor.submit(() -> saveBlocking("c"));
    IO.println("3 - forgotten Future: the task is started");

    // 4 - 线程:未捕获的异常使线程结束,并到达处理程序
    Thread.ofVirtual().name("recorder").start(() -> saveBlocking("d"));
    IO.println("4 - virtual thread started");

    // 5 - 启动但不等待,而是处理失败
    save("e").exceptionally(e -> {
        IO.println("5 - failure reported by exceptionally: " + e.getCause().getMessage());
        return null;
    });

    // 程序继续工作……
    for (int i = 1; i <= 4; i++) {
        sleep(100);
        IO.println("the program is working (" + i + ")");
    }
    executor.close();
    IO.println("normal end of the program");
}

// 200 毫秒后失败的异步操作
CompletableFuture<Void> save(String data) {
    return new CompletableFuture<Void>()
            .completeOnTimeout(null, 200, TimeUnit.MILLISECONDS)
            .thenRun(() -> {
                throw new IllegalStateException("failed to save [" + data + "]");
            });
}

// 同样的操作,以阻塞方式编写
void saveBlocking(String data) {
    sleep(200);
    throw new IllegalStateException("failed to save [" + data + "]");
}

// 没有受检异常的 Thread.sleep:中断会变成 CancellationException
void sleep(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new CancellationException("wait interrupted");
    }
}

结果:

> java Async12.java
1 - awaited CompletableFuture: exception caught: failed to save [a]
2 - forgotten CompletableFuture: the call has returned
3 - forgotten Future: the task is started
4 - virtual thread started
the program is working (1)
5 - failure reported by exceptionally: failed to save [e]
uncaught exception in [recorder] : failed to save [d]
the program is working (2)
the program is working (3)
the program is working (4)
normal end of the program

说明:

  • 第 4–5 行:[Thread.setDefaultUncaughtExceptionHandler] 设置当线程中的任何代码都没有捕获某个异常时、在该线程结束之前调用的处理器。没有它,JVM 会在错误输出中显示该异常的堆栈跟踪;
  • 第 8–12 行:该操作被等待,其异常被正常拦截;
  • 第 14–16 行:操作被启动,然后被遗忘。它的异常存储在 [CompletableFuture] 中,而永远不会有人去查看它:它就这样丢失了,连一条消息都没有;
  • 第 18–21 行:通过 [submit] 提交给执行器的任务也是如此:它的异常存储在返回的 [Future] 中,而该对象被忽略了;
  • 第 24 行:直接启动的线程没有 [Future]:它未能处理的异常会终止该线程,并到达未捕获异常处理器(结果的第 8 行)。不过,程序仍会继续;
  • 第 28–31 行:启动操作而不等待它的正确方式:为它附加一个处理失败的后续操作 [exceptionally] (或 [whenComplete]),这里是通过打印一条消息来处理(第 7 行);
  • 第 33–39 行表明,在所有情况下,程序都会继续运行直到正常结束。这与某些语言不同,在那些语言中,未捕获的异常可能终止程序;在 Java 中,它则悄无声息,这并没有更好:没有人看到的错误记录就意味着数据丢失。

因此规则是:已发起的操作必须被等待完成([join]、[get]、[allOf],或执行器的 [close] 方法,它会等待其任务),或者附加一个处理其失败的后续操作。代码分析工具(SpotBugs、IntelliJ IDEA 的检查)也可能会标记返回 [Future] 的方法的结果被忽略的情况。

9.6. 取消与截止时间

9.6.1. Future.cancel 与线程终止

长时间运行的操作必须能够被取消:用户点击了 [Cancel]、服务器客户端断开了连接、应用程序关闭了,或者发生了超时。Java 为此使用一种协作式机制——线程中断:

  • 线程的 [interrupt()] 方法会设置其中断标志;它并不会停止线程(强制停止的 [Thread.stop] 方法自 Java 20 起已被弃用:它会抛出 [UnsupportedOperationException]);
  • 如果线程阻塞在可中断的等待中([Thread.sleep]、[Object.wait]、[Thread.join]、[BlockingQueue.take]、[Future.get]……),等待会被立即中断,并触发 [InterruptedException],同时清除该标志;
  • 执行计算的线程会使用 [Thread.currentThread().isInterrupted()] 定期检查自己的标志,如果已设置,就优雅地终止;
  • 由执行器返回的 [cancel(true)] 方法,作用于 [Future] 时,会把任务转入 [CANCELLED] 状态,并中断执行它的线程([cancel(false)] 只是在任务尚未开始时阻止其启动)。取消之后,[get()] 会抛出 [CancellationException]。

这种机制是协作式的:没有人强行停止一个操作;操作会在能够干净地停止的时刻自行停止。这就是为什么拦截 [InterruptedException] 的方法不得忽略它:它必须要么将其传播出去,要么自行终止,或者至少用 [Thread.currentThread().interrupt()] 重置标志,以便调用代码知道已经请求了中断(我们的 [sleep] 方法就是这样做的)。

程序 [Async13.java] 以几种方式取消一个模拟的下载:

// 取消操作:Future.cancel(true) 与线程中断
long start = System.nanoTime();

void main() throws InterruptedException, ExecutionException {
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        // 1 - 我们最多等待结果 1.2 秒,然后取消该操作
        Future<?> download1 = executor.submit(() -> download(10));
        try {
            download1.get(1200, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            // cancel(true) 中断执行该任务的线程
            download1.cancel(true);
            display("1 - " + e.getClass().getSimpleName() + ", state: " + download1.state());
        }

        // 2 - 定期自我检查是否已被中断的计算
        start = System.nanoTime();
        Future<Long> computation = executor.submit(this::compute);
        Thread.sleep(300);
        computation.cancel(true);
        try {
            display("2 - result: " + computation.get());
        } catch (CancellationException e) {
            display("2 - get() throws " + e.getClass().getSimpleName() + ", state: " + computation.state());
        }
        Thread.sleep(100);

        // 3 - 程序在 700 毫秒后请求取消
        start = System.nanoTime();
        Future<?> download3 = executor.submit(() -> download(10));
        Thread.sleep(700);
        display("3 - the program requests the cancellation");
        download3.cancel(true);
        display("3 - isCancelled=" + download3.isCancelled());
        Thread.sleep(100);

        // 4 - CompletableFuture 上的 cancel() 不会中断它所代表的操作
        start = System.nanoTime();
        CompletableFuture<Void> download4 = CompletableFuture.runAsync(() -> download(3), executor);
        Thread.sleep(400);
        download4.cancel(true);
        display("4 - CompletableFuture cancelled: isCancelled=" + download4.isCancelled()
                + ", but the operation continues");
    } // close() 等待所有任务结束
}

// 模拟下载 [nbBlocks] 个数据块(每 300 毫秒一个块)
void download(int nbBlocks) {
    try {
        for (int i = 1; i <= nbBlocks; i++) {
            // 线程一被中断,阻塞等待就被中断
            Thread.sleep(300);
            display("  block " + i + "/" + nbBlocks + " received");
        }
    } catch (InterruptedException e) {
        display("  download interrupted");
    }
}

// 一个长时间的计算,每 1,000,000 轮检查一次其线程的中断标志
long compute() {
    long sum = 0;
    for (long i = 0; i < 100_000_000_000L; i++) {
        if (i % 1_000_000 == 0 && Thread.currentThread().isInterrupted()) {
            display("  computation interrupted at round " + i);
            return -1;
        }
        sum += i % 7;
    }
    return sum;
}

// 显示自 [start] 以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

结果:

> java Async13.java
  318 ms :   block 1/10 received
  638 ms :   block 2/10 received
  939 ms :   block 3/10 received
 1212 ms :   download interrupted
 1214 ms : 1 - TimeoutException, state: CANCELLED
  301 ms : 2 - get() throws CancellationException, state: CANCELLED
  303 ms :   computation interrupted at round 131000000
  302 ms :   block 1/10 received
  603 ms :   block 2/10 received
  701 ms : 3 - the program requests the cancellation
  702 ms :   download interrupted
  702 ms : 3 - isCancelled=true
  309 ms :   block 1/3 received
  404 ms : 4 - CompletableFuture cancelled: isCancelled=true, but the operation continues
  609 ms :   block 2/3 received
  910 ms :   block 3/3 received

说明:

  • 第 47–58 行:模拟的下载每 300 毫秒接收一个数据块。它由一个虚拟线程执行,并使用阻塞等待 [Thread.sleep],该等待在线程被中断时立即终止:[InterruptedException] 使循环退出,下载就此停止,并以此作为信号。它无需任何特殊参数就可以被取消:[java.util.concurrent] 中的等待对中断的反应方式相同,在虚拟线程中,套接字上的阻塞 I/O 操作也是如此(此时套接字被关闭,操作会抛出 [SocketException]);
  • 第 6–14 行:[get(1200, TimeUnit.MILLISECONDS)] 最多等待结果 1.2 秒,然后抛出 [TimeoutException]。等待被放弃,但操作并未放弃:它通过 [cancel(true)] 被显式取消,这会中断下载的虚拟线程。该线程收到了三个数据块,并在 1,200 毫秒时停止(结果的第 2–6 行);
  • 第 16–26 行:一个可取消的计算(不是等待)。[compute] 方法(第 60–71 行)每一百万次循环检查一次其线程的中断标志,如果已设置就停止。程序在 300 毫秒后中止它:[get()] 立即抛出 [CancellationException] (第 7 行),而计算在此后不久自行停止(第 8 行);
  • 第 28–35 行:程序在 700 毫秒后请求取消。它立即生效:对第三个数据块的等待被中断(第 11–13 行);
  • 第 37–43 行:一个需要注意的陷阱。*[cancel] 方法作用于 *[CompletableFuture] 时,会使后者以 *[CANCELLED] 状态终止,但它不会中断任何东西:[CompletableFuture] 不知道有哪个线程(如果有的话)在为它工作(其 [mayInterruptIfRunning] 参数被忽略)。下载会继续直到完成(第 16–17 行);只是它的结果会被忽略。要让 [CompletableFuture] 能够停止它所代表的操作,该操作必须监视 [CompletableFuture] 的状态([isCancelled()]),或者必须保留 [Future]* 或任务的线程以便中断它;
  • 第 44 行:执行器的 [close()] 方法等待所有任务完成,包括步骤 4 中的那个任务。

9.6.2. 多个过程,多种结果

程序 [Async14.java] 启动五个持续 1 到 5 秒的过程:3 号过程抛出异常,4 号过程被取消。它在每个任务结束时立即处理它,无论其以何种方式结束,并且始终知道它是哪个任务:

// 由虚拟线程执行的五个耗时 1 到 5 秒的处理:
// 第 3 号抛出异常,第 4 号被取消
long start;

void main() throws InterruptedException {
    start = System.nanoTime();
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
         ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor()) {
        // CompletionService 会在每个任务一结束就交付它
        CompletionService<ProcessingResult> service = new ExecutorCompletionService<>(executor);
        List<Future<ProcessingResult>> tasks = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            int number = i;
            tasks.add(service.submit(() -> sleep(number, number + 1)));
        }
        // 我们在 2.5 秒后取消第 4 号处理
        scheduler.schedule(() -> tasks.get(4).cancel(true), 2500, TimeUnit.MILLISECONDS);
        display("the " + tasks.size() + " processings are started");

        // 无论以何种方式结束,我们都在每个处理一结束就使用它
        for (int i = 0; i < tasks.size(); i++) {
            Future<ProcessingResult> task = service.take();
            int number = tasks.indexOf(task);
            String outcome = switch (task.state()) {
                case SUCCESS -> String.format("finished: scheduled duration %d s, actual duration %.1f s",
                        task.resultNow().duration(), task.resultNow().actualDuration());
                case FAILED -> "encountered the following error: " + task.exceptionNow().getMessage();
                case CANCELLED -> "cancelled";
                case RUNNING -> "still running?";
            };
            display("processing " + number + " " + outcome);
        }
    }
}

// 处理:休眠 [duration] 秒,按一秒为一片
ProcessingResult sleep(int number, int duration) throws InterruptedException {
    long processingStart = System.nanoTime();
    // 第 3 号处理的异常
    if (number == 3) {
        throw new IllegalStateException("test....");
    }
    for (int i = 1; i <= duration; i++) {
        Thread.sleep(1000);
    }
    // 返回给调用者的结果
    return new ProcessingResult(duration, (System.nanoTime() - processingStart) / 1e9);
}

// 一个处理的结果
record ProcessingResult(int duration, double actualDuration) {
}

// 显示自开始以来经过的时间,以秒为单位
void display(String message) {
    IO.println(String.format("%4.1f s : %s", (System.nanoTime() - start) / 1e9, message));
}

结果:

1
2
3
4
5
6
7
> java Async14.java
 0.0 s : the 5 processings are started
 0.0 s : processing 3 encountered the following error: test....
 1.0 s : processing 0 finished: scheduled duration 1 s, actual duration 1.0 s
 2.0 s : processing 1 finished: scheduled duration 2 s, actual duration 2.0 s
 2.5 s : processing 4 cancelled
 3.0 s : processing 2 finished: scheduled duration 3 s, actual duration 3.0 s

说明:

  • 第 36–48 行:该过程。3 号抛出异常;其他的按一秒的间隔“休眠” [duration] 秒,使用可中断的 [Thread.sleep],并返回一个结果——一个 [record]——其中包含预定的时长和实际的时长。该方法声明了 [InterruptedException]:它由 [Callable] 调用,其方法 [call] 可以抛出受检异常;
  • 第 7–8 行:在同一个 [try] 中声明的两个执行器:虚拟线程执行器,以及一个 [ScheduledExecutorService],即能够在延迟之后执行任务的执行器(我们将在关于时间的一节中再讨论它);
  • 第 10–15 行:这五个过程被提交给已在 [CompletionService] [Async10.java] 中遇到过的 [Future] 实例 ,并存储在一个列表中;
  • 第 17 行:[ScheduledExecutorService] 将在 2.5 秒后取消 4 号过程,尽管它还有 2.5 秒才能运行完;
  • 第 21–32 行:[take()] 在每个过程一完成就交付它,无论其以何种方式结束:被取消的 [Future] 同样会被交付。我们不调用会抛出异常的 [get()],而是使用涵盖 [Future] 四个常量的 [switch] 表达式来检查 [Future.State] 的状态(编译器会验证没有遗漏)。处理编号由其 [Future] 在列表中的位置([indexOf])确定;
  • 结果显示,3 号立即失败,0、1 和 2 号分别在 1、2 和 3 秒后结束,而 4 号在 2.5 秒时被取消。

9.6.3. 限制等待的时长

程序 [Async15.java] 提供了限制等待时长的工具:[CompletableFuture] 的方法 [orTimeout] 和 [completeOnTimeout] (Java 9),以及 [Future] 带延时的 [get] 方法。它还展示了如何组合两种停止原因。

// 限制等待的时长:orTimeout、completeOnTimeout、get(timeout)
long start = System.nanoTime();

void main() throws InterruptedException, ExecutionException {
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        // 1 - orTimeout:我们最多等待一秒
        CompletableFuture<String> slow = CompletableFuture.supplyAsync(
                () -> queryBlocking("slow-server", 3000), executor);
        try {
            display("1 - answer: " + slow.orTimeout(1, TimeUnit.SECONDS).join());
        } catch (CompletionException e) {
            display("1 - " + e.getCause().getClass().getSimpleName() + ", state: " + slow.state());
        }
        // 操作本身继续:我们让它完成
        Thread.sleep(2200);

        // 2 - completeOnTimeout:超过一秒,我们接受默认的回答
        start = System.nanoTime();
        String answer = query("slow-server", 3000)
                .completeOnTimeout("default answer", 1, TimeUnit.SECONDS)
                .join();
        display("2 - " + answer);

        // 3 - 要真正停止操作,我们中断执行它的线程
        start = System.nanoTime();
        Future<String> slow3 = executor.submit(() -> queryBlocking("slow-server", 3000));
        try {
            display("3 - answer: " + slow3.get(1, TimeUnit.SECONDS));
        } catch (TimeoutException e) {
            slow3.cancel(true);
            display("3 - one-second timeout exceeded, operation cancelled, state: " + slow3.state());
        }
    }

    // 4 - 两种停止原因:每个处理自己的超时和一个全局停止
    start = System.nanoTime();
    CompletableFuture<Void> generalStop = new CompletableFuture<>();
    CompletableFuture<Void> all = CompletableFuture.allOf(
            processWithTimeout("fast", 500, 1000, generalStop),
            processWithTimeout("slow", 3000, 1000, generalStop),
            processWithTimeout("medium", 1500, 2000, generalStop));
    // 调用者在 1,200 毫秒后请求全局停止
    Thread.sleep(1200);
    display("4 - general stop requested");
    generalStop.complete(null);
    all.join();
}

// 一个限时 [timeout] 毫秒的处理,调用者也可以停止它
CompletableFuture<Void> processWithTimeout(String name, int duration, int timeout, CompletableFuture<Void> stop) {
    CompletableFuture<String> answer = query(name, duration).orTimeout(timeout, TimeUnit.MILLISECONDS);
    // 全局停止会取消对回答的等待
    stop.thenRun(() -> answer.cancel(false));
    // 我们检查等待是如何结束的
    return answer.handle((text, e) -> switch (e) {
        case null -> text;
        case TimeoutException _ -> name + " : timeout of " + timeout + " ms exceeded";
        case CancellationException _ -> name + " : stopped at the caller's request";
        default -> name + " : " + e;
    }).thenAccept(message -> display("4 - " + message));
}

// 模拟一个在 [duration] 毫秒后回答的服务器
CompletableFuture<String> query(String server, int duration) {
    return new CompletableFuture<String>()
            .completeOnTimeout(server + " answered in " + duration + " ms", duration, TimeUnit.MILLISECONDS);
}

// 同样的操作,以阻塞方式编写
String queryBlocking(String server, int duration) {
    try {
        Thread.sleep(duration);
        display("  " + server + " has finished its work");
        return server + " answered in " + duration + " ms";
    } catch (InterruptedException e) {
        display("  " + server + " was interrupted");
        throw new CancellationException("operation interrupted");
    }
}

// 显示自 [start] 以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

结果:

> java Async15.java
 1028 ms : 1 - TimeoutException, state: FAILED
 3025 ms :   slow-server has finished its work
 1001 ms : 2 - default answer
 1003 ms :   slow-server was interrupted
 1004 ms : 3 - one-second timeout exceeded, operation cancelled, state: CANCELLED
  501 ms : 4 - fast answered in 500 ms
 1005 ms : 4 - slow : timeout of 1000 ms exceeded
 1206 ms : 4 - general stop requested
 1207 ms : 4 - medium : stopped at the caller's request

说明:

  • 第 7–8 行:慢速操作是一个阻塞方法(第 69–79 行),通过带执行器的 [supplyAsync] 由虚拟线程执行;
  • 第 10 行:如果 [orTimeout(timeout, unit)] [CompletableFuture] 在时限内没有完成,它就用 [TimeoutException] 终止它。这是对 [anyOf] 在 [Async09.java] 程序中的“竞赛”的直接写法。[orTimeout] 不会创建新的 [CompletableFuture]:它修改的是它所作用的那个(并返回它);这就是为什么 [slow] 的状态是 [FAILED] (结果的第 2 行);
  • 第 14–15 行:[orTimeout] 中止的是等待,而不是操作:虚拟线程继续运行,并在 3 秒时完成其工作(第 3 行),但已毫无用处。这与前面 [cancel] 遇到的问题相同:[CompletableFuture] 无法中断它所代表的操作;
  • 第 17–22 行:如果 [completeOnTimeout(value, timeout, unit)] [CompletableFuture] 在时限内没有完成,就用一个默认值终止它:一秒之后返回一个“默认答案”(第 4 行);
  • 第 24–32 行:为了真正停止该操作,把它提交给执行器;我们最多等待它的 [Future] 一秒钟,然后用 [cancel(true)] 取消它,这会中断它的线程:操作在 1 秒后停止(第 5–6 行)。当操作是阻塞且可中断的时,这是首选方案;
  • 第 49–61 行:一个过程可能因多种原因而停止;这里是其自身的超时和调用者发出的全局停止请求:
    • 第 51 行:过程自身的超时通过 [orTimeout] 设置;
    • 第 53 行:全局终止本身就是一个 [CompletableFuture<Void>],由调用者来终止它;为它附加了一个后续操作,用于取消对响应的等待;
    • 第 55–60 行:无论原因是什么,等待都以失败告终;[handle] 使用对类型的 [switch] (Java 21)来检查异常:[case null] 表示成功,[case TimeoutException _] 表示超时,[case CancellationException _] 表示全局终止。字符 [_] (Java 22)是匿名变量:测试类型时无需为对象命名;
  • 第 36–46 行:三个过程,以及在 1,200 毫秒时、在 [CompletableFuture] 和 [generalStop] 完成时请求的全局关闭。过程 [fast] 正常完成;过程 [slow] 超过了它一秒的时限;过程 [medium] 被分配了两秒,但被全局关闭终止(第 7–10 行)。

9.7. 报告进度

长时间运行的操作通常需要报告其进度(进度条、百分比)。最简单的方法是给它传入一个接收进度报告的回调函数 :[Consumer<T>],即第 7 章中的函数式接口,其唯一的方法 [accept(T)] 接受一个值。操作在每一步调用 [accept];它并不知道进度报告将如何显示。

在图形用户界面中,由执行操作的线程生成的报告不能直接更新图形组件:[Consumer] 必须把更新委托给 UI 线程(在 Swing 中使用 [SwingUtilities.invokeLater(() -> bar.setValue(percentage))],在 JavaFX 中使用 [Platform.runLater])。在控制台程序中,它可以直接显示输出。程序 [Async16.java] 模拟一次文件复制,用户可以通过输入 [Enter] 来取消它:

// 用 Consumer 报告操作的进度;用户可以取消它
void main() throws InterruptedException {
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        IO.println("Copy in progress, press [Enter] to cancel it");
        // 复制由虚拟线程执行;display 方法显示其报告
        Future<Integer> copy = executor.submit(() -> copy(8, this::display));
        // 另一个虚拟线程等待用户按 [Enter] 来取消复制
        Thread.ofVirtual().start(() -> {
            // 如果标准输入已关闭,readln 返回 null:我们不取消任何东西
            if (IO.readln() != null) {
                copy.cancel(true);
            }
        });
        try {
            IO.println("Copy finished: " + copy.get() + " files copied");
        } catch (CancellationException e) {
            IO.println("Copy cancelled by the user");
        } catch (ExecutionException e) {
            IO.println("Copy failed: " + e.getCause());
        }
    }
}

// 操作不知道其进度如何显示:它只负责报告
int copy(int nbFiles, Consumer<Progress> progress) throws InterruptedException {
    for (int i = 1; i <= nbFiles; i++) {
        // 复制文件
        Thread.sleep(300);
        // 进度报告(调用者可能不需要:此时 progress 为 null)
        if (progress != null) {
            progress.accept(new Progress(100 * i / nbFiles, "file" + i + ".dat"));
        }
    }
    return nbFiles;
}

// 一份进度报告
record Progress(int percentage, String file) {
}

// 在控制台显示进度报告:一个 20 个字符的进度条
void display(Progress progress) {
    int nbHashes = progress.percentage() / 5;
    String bar = "#".repeat(nbHashes) + ".".repeat(20 - nbHashes);
    IO.println(String.format("[%s] %3d %% %s", bar, progress.percentage(), progress.file()));
}

未取消时的结果:

> java Async16.java
Copy in progress, press [Enter] to cancel it
[##..................]  12 % file1.dat
[#####...............]  25 % file2.dat
[#######.............]  37 % file3.dat
[##########..........]  50 % file4.dat
[############........]  62 % file5.dat
[###############.....]  75 % file6.dat
[#################...]  87 % file7.dat
[####################] 100 % file8.dat
Copy finished: 8 files copied

用户在复制操作期间约一秒半后输入 [Enter] 时的结果:

1
2
3
4
5
6
7
8
> java Async16.java
Copy in progress, press [Enter] to cancel it
[##..................]  12 % file1.dat
[#####...............]  25 % file2.dat
[#######.............]  37 % file3.dat
[##########..........]  50 % file4.dat
[############........]  62 % file5.dat
Copy cancelled by the user

说明:

  • 第 24–35 行:该操作接收一个 [Consumer<Progress>]。在每个文件之后,它使用 [Progress] 对象(一个包含百分比和文件名的 [record] )报告其进度。不需要报告的调用者传入 [null],因此第 30 行有相应的检查;
  • 第 41–46 行:显示报告:一个使用 [String.repeat] (Java 11)构造的 20 个字符的进度条。方法引用 [this::display] (第 6 行)就是传给该操作的 [Consumer<Progress>];
  • 第 6 行:复制由一个虚拟线程执行;
  • 第 8–13 行:另一个虚拟线程等待用户输入 [Enter] ([IO.readln()] 是阻塞式读取,这正是使用这个单独线程的原因:被阻塞的是这个线程,而不是整个程序),然后通过 [cancel(true)] 取消复制,这会中断第 28 行的 [Thread.sleep] 。程序不会等待它:它是守护线程,如果用户没有输入任何内容,它会在程序结束时被丢弃;
  • 第 14–20 行:程序等待复制结束。取消会导致 [CancellationException],而复制失败则会导致 [ExecutionException]。

9.8. 异步输入/输出

9.8.1. 文件

I/O 正是异步处理存在的根本原因。Java 为文件提供了两类类:

  • “经典”的阻塞类:[Files] ([readAllLines]、[readString]、[lines]、[writeString]、[newBufferedReader]、[newBufferedWriter]……)、[BufferedReader]、[BufferedWriter]。当你不想阻塞重要线程时,现在可以在虚拟线程上执行这些类;
  • [AsynchronousFileChannel] 类(Java 7),其操作返回一个 [Future] 或调用一个 [CompletionHandler]。它很少被使用:在 Linux 上,它实际上是在 JVM 内部的线程池上执行阻塞读取,而且它的接口很繁琐。

程序 [Async17.java] 通过从主程序读取位于程序目录中的税率档文件 [TaxData.txt] 来展示这两类类:

1
2
3
4
5
6
7
4962:0:0
8382:0.068:291.09
14753:0.191:1322.92
23888:0.283:2668.39
38868:0.374:4846.98
47932:0.426:6883.66
0:0.481:9505.54

每一行包含税率档的阈值、系数 [coeffR] 和系数 [coeffN],以字符 [:] 分隔,并使用小数点书写(税率表是 2003 年收入适用的 2004 年税率表,在本练习中原样保留)。程序在 [09-async] 文件夹中运行,并在当前文件夹中查找它的文件。

// 文件输入 / 输出:AsynchronousFileChannel,然后是虚拟线程上的阻塞 I/O
final Path data = Path.of("TaxData.txt");
final Path report = Path.of("report-17.txt");

void main() throws InterruptedException {
    // 1 - AsynchronousFileChannel(Java 7):异步读取,以 CompletableFuture 返回
    String content = readAsynchronously(data).join();
    IO.println("1 - AsynchronousFileChannel: " + content.lines().count() + " lines");

    // 2 到 7 - 普通的阻塞 I/O,由虚拟线程执行
    Thread.ofVirtual().start(() -> {
        try {
            processFiles();
        } catch (IOException e) {
            IO.println("error: " + e);
        }
    }).join();
}

// 用 AsynchronousFileChannel 读取整个(小)文件
CompletableFuture<String> readAsynchronously(Path file) {
    CompletableFuture<String> result = new CompletableFuture<>();
    try {
        AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
        ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
        // 读取已启动;回调对象将完成 CompletableFuture
        channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer nbBytes, ByteBuffer read) {
                result.complete(new String(read.array(), 0, nbBytes, StandardCharsets.UTF_8));
            }

            @Override
            public void failed(Throwable e, ByteBuffer read) {
                result.completeExceptionally(e);
            }
        });
        // 读取结束时通道将被关闭,无论结果如何
        result.whenComplete((text, e) -> close(channel));
    } catch (IOException e) {
        result.completeExceptionally(e);
    }
    return result;
}

void processFiles() throws IOException {
    // 2 - 一次操作读取整个文件
    List<String> lines = Files.readAllLines(data);
    IO.println("2 - Files.readAllLines: " + lines.size() + " lines");

    // 3 - 用 BufferedReader 逐行读取
    List<TaxBracket> brackets = new ArrayList<>();
    try (BufferedReader reader = Files.newBufferedReader(data)) {
        String line;
        // 到达文件末尾时 readLine 返回 null
        while ((line = reader.readLine()) != null) {
            brackets.add(TaxBracket.parse(line));
        }
    }
    IO.println("3 - BufferedReader.readLine: " + brackets.size() + " brackets, 2nd: " + brackets.get(1));

    // 4 - Files.lines 返回按需读取的行 Stream
    try (Stream<String> stream = Files.lines(data)) {
        IO.println("4 - Files.lines: " + stream.count() + " lines");
    }

    // 5 - 用 BufferedWriter 写入
    try (BufferedWriter writer = Files.newBufferedWriter(report)) {
        writer.write("Brackets of the tax scale (exercise: 2004 tax scale on 2003 income)");
        writer.newLine();
        for (int i = 0; i < brackets.size(); i++) {
            TaxBracket bracket = brackets.get(i);
            String limit = bracket.limit().signum() == 0 ? "beyond"
                    : String.format("up to %,d €", bracket.limit().intValue());
            writer.write(String.format("bracket %d : %-18s rate %.1f %%",
                    i + 1, limit, bracket.coeffR().multiply(BigDecimal.valueOf(100))));
            writer.newLine();
        }
    }

    // 6 - 将整个文件读取为字符串
    String text = Files.readString(report);
    IO.print("5 and 6 - content of [" + report + "] :\n" + text);

    // 7 - 追加到文件末尾,然后删除它
    Files.writeString(report, "end of the report\n", StandardOpenOption.APPEND);
    IO.println("7 - last line: " + Files.readAllLines(report).getLast());
    Files.delete(report);
}

// 关闭通道,不抛出受检异常
void close(Channel channel) {
    try {
        channel.close();
    } catch (IOException e) {
        IO.println("error while closing: " + e);
    }
}

// 一个税率档;文件使用小数点,BigDecimal 能够理解
record TaxBracket(BigDecimal limit, BigDecimal coeffR, BigDecimal coeffN) {
    static TaxBracket parse(String line) {
        String[] fields = line.split(":");
        return new TaxBracket(new BigDecimal(fields[0]), new BigDecimal(fields[1]),
                new BigDecimal(fields[2]));
    }
}

结果:

> java Async17.java
1 - AsynchronousFileChannel: 7 lines
2 - Files.readAllLines: 7 lines
3 - BufferedReader.readLine: 7 brackets, 2nd: TaxBracket[limit=8382, coeffR=0.068, coeffN=291.09]
4 - Files.lines: 7 lines
5 and 6 - content of [report-17.txt] :
Brackets of the tax scale (exercise: 2004 tax scale on 2003 income)
bracket 1 : up to 4,962 €      rate 0.0 %
bracket 2 : up to 8,382 €      rate 6.8 %
bracket 3 : up to 14,753 €     rate 19.1 %
bracket 4 : up to 23,888 €     rate 28.3 %
bracket 5 : up to 38,868 €     rate 37.4 %
bracket 6 : up to 47,932 €     rate 42.6 %
bracket 7 : beyond             rate 48.1 %
7 - last line: end of the report

说明:

  • 第 20–44 行:使用 [AsynchronousFileChannel] 读取,以 [CompletableFuture<String>] 的形式呈现。这是把带有回调方法的 API 转换为 [CompletableFuture] 的通用技术:我们创建一个“进行中”的 [CompletableFuture] (第 22 行),立即返回它(第 43 行),由回调方法来完成它,返回结果([complete],第 30 行)或异常([completeExceptionally],第 35 行)。回调对象是一个实现了 [CompletionHandler<Integer, ByteBuffer>] 的匿名类:读取操作的结果是读取的字节数,而这里传入的对象就是缓冲区本身。对于小文件,一次读取操作就足够了;大文件则需要连续多次读取,回调方法必须把这些读取串联起来;
  • 第 39 行:[whenComplete] 在读取操作完成时关闭通道,无论读取成功与否;
  • 第 11–17 行:其他操作都是普通的阻塞 I/O 操作,被归入 [processFiles] 方法中,并由虚拟线程执行。[Runnable] 的 lambda 不能抛出受检异常:[IOException] 在 lambda 内部被拦截;
  • 第 48 行:[Files.readAllLines] 读取整个文件并返回其各行的列表(默认使用 UTF-8,与 [Files] 的所有方法一样);
  • 第 52–59 行:使用 [BufferedReader] 逐行读取;[readLine()] 在文件末尾返回 [null]。每一行都由记录的 [parse] 方法(第 100–107 行)转换为 [TaxBracket];这些数字是 [BigDecimal],其构造函数要求使用小数点,而不论机器的语言如何。记录由其 [toString] 方法生成的表示形式出现在结果的第 4 行;
  • 第 63–65 行:[Files.lines] 返回一个由按需读取的行组成的 [Stream<String>] :与 [readAllLines] 不同,它不会把整个文件加载到内存中。这是处理大文件的首选方法。该流会保持文件处于打开状态:必须将其关闭,因此使用了带资源的 [try] ;
  • 第 68–79 行:使用 [BufferedWriter] 写入,它在退出 [try] 时被关闭(因而刷新到磁盘)。[%,d] 格式会插入与机器语言相符的千位分隔符(在法语中是一个窄的不间断空格);
  • 第 82–88 行:[Files.readString] (Java 11)重新读取写入的文件;[Files.writeString] 使用 [StandardOpenOption.APPEND] 选项向其中添加一行;[getLast()] (Java 21)返回列表的最后一个元素,然后删除该文件。

回想前面提到的局限:文件读写在操作期间会把虚拟线程固定在其载体线程上,而 JVM 通过增加一个载体线程来进行补偿。对于本地文件,这很少会被察觉;而对于网络操作,虚拟线程在等待期间确实会释放其载体线程。

9.8.2. 网络:HttpClient

Java 的 HTTP 客户端 [java.net.http.HttpClient] (Java 11)同时提供两种方式:[send],它是阻塞的并返回响应;以及 [sendAsync],它立即返回一个包含响应的 [CompletableFuture] 。第 12 章将详细讨论这一点;程序 [Async18.java] 只是通过查询一个本地的小型 HTTP 服务器来比较这两种方法,该服务器需要一秒钟才返回某个城市的“温度”:

// HttpClient:对一个小型本地服务器发出异步(sendAsync)或阻塞(send)HTTP 请求
import com.sun.net.httpserver.HttpServer;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

final int port = 27510;
final List<String> cities = List.of("Angers", "Brest", "Colmar", "Dijon", "Évry", "Foix");
long start;

void main() throws IOException, InterruptedException, ExecutionException {
    // 一个需要一秒钟才给出某城市“温度”的 HTTP 服务器
    HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), port), 0);
    server.createContext("/temperature", exchange -> {
        // 请求的形式为 /temperature?city=xxx
        String parameter = exchange.getRequestURI().getRawQuery().substring("city=".length());
        String city = URLDecoder.decode(parameter, StandardCharsets.UTF_8);
        sleep(1000);
        byte[] response = (city + " : " + (10 + city.length()) + " °C").getBytes(StandardCharsets.UTF_8);
        exchange.sendResponseHeaders(200, response.length);
        try (OutputStream stream = exchange.getResponseBody()) {
            stream.write(response);
        }
    });
    // 每个收到的请求由一个虚拟线程处理
    server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
    server.start();

    try (HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build()) {
        // 先发一个请求,让 JVM 在测量之前加载客户端类
        client.send(request("Paris"), HttpResponse.BodyHandlers.discarding());

        // 1 - sendAsync 立即返回 CompletableFuture<HttpResponse<String>>
        start = System.nanoTime();
        List<CompletableFuture<String>> responses = cities.stream()
                .map(city -> client.sendAsync(request(city), HttpResponse.BodyHandlers.ofString())
                        .thenApply(HttpResponse::body))
                .toList();
        CompletableFuture.allOf(responses.toArray(CompletableFuture[]::new)).join();
        display("1 - sendAsync: " + responses.stream().map(CompletableFuture::resultNow).toList());

        // 2 - send 是阻塞的:我们从虚拟线程调用它
        start = System.nanoTime();
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<String>> responses2 = new ArrayList<>();
            for (String city : cities) {
                responses2.add(executor.submit(
                        () -> client.send(request(city), HttpResponse.BodyHandlers.ofString()).body()));
            }
            List<String> texts = new ArrayList<>();
            for (Future<String> response : responses2) {
                texts.add(response.get());
            }
            display("2 - send on virtual threads: " + texts);
        }
    } finally {
        server.stop(0);
    }
}

// 询问某城市温度的 GET 请求
HttpRequest request(String city) {
    String parameter = URLEncoder.encode(city, StandardCharsets.UTF_8);
    URI address = URI.create("http://localhost:" + port + "/temperature?city=" + parameter);
    return HttpRequest.newBuilder(address).build();
}

// 没有受检异常的 Thread.sleep:中断会变成 CancellationException
void sleep(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new CancellationException("wait interrupted");
    }
}

// 显示自 [start] 以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

结果:

1
2
3
> java Async18.java
 1033 ms : 1 - sendAsync: [Angers : 16 °C, Brest : 15 °C, Colmar : 16 °C, Dijon : 15 °C, Évry : 14 °C, Foix : 14 °C]
 1023 ms : 2 - send on virtual threads: [Angers : 16 °C, Brest : 15 °C, Colmar : 16 °C, Dijon : 15 °C, Évry : 14 °C, Foix : 14 °C]

说明:

  • 第 12–27 行:服务器。这个 JVM 文件包含一个小型 HTTP 服务器,即来自 [HttpServer] 模块 [jdk.httpserver] 的类,在第 2 行导入(紧凑文件只会自动导入 [java.base] 模块;来自 [java.net.http] 模块的客户端类在第 3–5 行导入)。[createContext] 把一个处理器与 [/temperature] 路径关联起来——这是一个接收 HTTP 交换的 lambda:它从请求的地址中解码 [city] 参数,等待一秒,然后发送响应。第 26 行让每个请求由一个虚拟线程处理:以这种方式配置的服务器可以为数千个等待中的客户端提供服务;
  • 第 29–31 行:客户端由一个构造方法([newBuilder])创建,这里它设置了协议版本。自 Java 21 起,它实现了 [AutoCloseable] ,并在带资源的 [try] 中声明。先发出一个初始请求来“预热”JVM:客户端第一次使用时会加载大量类,这会使后续的测量偏差几百毫秒;
  • 第 33–40 行:[sendAsync(request, handler)] 发送请求并立即返回 [CompletableFuture<HttpResponse<String>>];主体处理器 [BodyHandlers.ofString()] 指示响应主体必须作为字符串读取。[thenApply(HttpResponse::body)] 只保留主体。六个请求同时发送,它们的响应在一秒后一起到达(结果的第 2 行)。在等待期间,没有线程在等待响应:客户端通过一个“选择器”线程来监视其连接;
  • 第 42–55 行:[send] 是阻塞的;它在六个虚拟线程中被调用。结果相同:六个请求总共耗时一秒(第 3 行),并且没有系统线程被阻塞;
  • 第 61–66 行:GET 请求。[URLEncoder.encode] 对不能原样出现在地址中的字符(Évry 中的 [É] )进行编码,服务器使用 [URLDecoder.decode] 对其解码(第 17 行)。

9.9. 异步值流

异步操作在一段时间之后返回一个结果。流([Stream])或迭代器则按需返回一个序列的值。有时需要把两者结合起来:一个值序列,其中每个值在产生之前都需要等待。文件中的大量行、SQL 查询结果中的行、通过网络连接到达的消息、传感器读数……都属于这种情况。其他语言为此提供了专用类型;Java 提供两种模型:

  • “拉取”模型:消费者请求下一个值并等待其可用。使用虚拟线程时,这就是一个由虚拟线程读取的、每个值的产生都会阻塞的 [Iterator] 或 [Stream];
  • “推送”模型:生产者在值产生时把它们发送给订阅者,由订阅者控制吞吐量。这就是响应式流模型,由 [java.util.concurrent.Flow] 接口(Java 9)标准化。

9.9.1. 拉取模型:由虚拟线程读取的 Stream

程序 [Async19.java] 以 [Stream<Measurement>] 的形式产生测量值——每 200 毫秒一个:

// 带等待地产生的值序列:由虚拟线程读取的“阻塞”Stream
long start;

void main() throws InterruptedException {
    // 所有工作由一个虚拟线程完成:它的等待不会阻塞任何载体线程
    Thread.ofVirtual().start(this::consume).join();
}

void consume() {
    start = System.nanoTime();
    // 1 - 每个值一产生就被处理
    try (Stream<Measurement> measurements = readMeasurements("sensor-1", 4)) {
        measurements.forEach(measurement -> display("1 - received " + measurement));
    }

    // 2 - 我们可以在结束之前离开循环:生产者不会产生后续的值
    start = System.nanoTime();
    try (Stream<Measurement> measurements = readMeasurements("sensor-2", 100)) {
        Iterator<Measurement> iterator = measurements.iterator();
        while (iterator.hasNext()) {
            Measurement measurement = iterator.next();
            display("2 - received " + measurement);
            if (measurement.value() >= 22) {
                break;
            }
        }
    }

    // 3 - 取消:另一个线程中断读取该流的线程
    start = System.nanoTime();
    Thread reader = Thread.ofVirtual().start(() -> {
        try (Stream<Measurement> measurements = readMeasurements("sensor-3", 100)) {
            measurements.forEach(measurement -> display("3 - received " + measurement));
        } catch (CancellationException e) {
            display("3 - reading cancelled");
        }
    });
    waitForEnd(reader, 700);

    // 4 - Stream API 的所有操作都适用于该流
    start = System.nanoTime();
    String high;
    try (Stream<Measurement> measurements = readMeasurements("sensor-4", 6)) {
        high = measurements
                .filter(measurement -> measurement.value() > 21)
                .map(measurement -> NumberFormat.getInstance().format(measurement.value()))
                .collect(Collectors.joining(" ; ", "[", "]"));
    }
    display("4 - measurements above 21: " + high);
}

// 生产者:每 200 毫秒一次测量,仅在消费者请求时才产生
Stream<Measurement> readMeasurements(String sensor, int count) {
    return IntStream.rangeClosed(1, count)
            .mapToObj(i -> {
                // 等待下一次测量
                sleep(200);
                return new Measurement(sensor, i, 19.5 + i * 0.75);
            })
            // 由 close() 执行:正常结束时、break 之后或取消时
            .onClose(() -> IO.println("          " + sensor + " : end of production"));
}

// 等待线程结束 [timeout] 毫秒,然后中断它并等待其结束
void waitForEnd(Thread thread, long timeout) {
    try {
        thread.join(timeout);
        thread.interrupt();
        thread.join();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

// 没有受检异常的 Thread.sleep:中断会变成 CancellationException
void sleep(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new CancellationException("wait interrupted");
    }
}

// 显示自 [start] 以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

// 一次测量
record Measurement(String sensor, int number, double value) {
    @Override
    public String toString() {
        return sensor + " no. " + number + " : " + NumberFormat.getInstance().format(value) + " °C";
    }
}

结果:

> java Async19.java
  249 ms : 1 - received sensor-1 no. 1 : 20.25 °C
  455 ms : 1 - received sensor-1 no. 2 : 21 °C
  656 ms : 1 - received sensor-1 no. 3 : 21.75 °C
  857 ms : 1 - received sensor-1 no. 4 : 22.5 °C
          sensor-1 : end of production
  200 ms : 2 - received sensor-2 no. 1 : 20.25 °C
  401 ms : 2 - received sensor-2 no. 2 : 21 °C
  603 ms : 2 - received sensor-2 no. 3 : 21.75 °C
  804 ms : 2 - received sensor-2 no. 4 : 22.5 °C
          sensor-2 : end of production
  201 ms : 3 - received sensor-3 no. 1 : 20.25 °C
  402 ms : 3 - received sensor-3 no. 2 : 21 °C
  602 ms : 3 - received sensor-3 no. 3 : 21.75 °C
          sensor-3 : end of production
  702 ms : 3 - reading cancelled
          sensor-4 : end of production
 1206 ms : 4 - measurements above 21: [21.75 ; 22.5 ; 23.25 ; 24]

说明:

  • 第 52–62 行:生产者。它返回一个由从 1 到 [Stream<Measurement>] [count] 的整数构造的流;[mapToObj] 函数等待 200 毫秒,然后返回一个测量值。由于流是惰性的,这个函数只有在消费者请求下一个值时才会被调用,每个测量值都在产生下一个之前被处理。[onClose] 记录一个在流关闭时执行的动作,无论原因如何:这就是生产者的 [finally];
  • 第 6 行:所有工作都由一个虚拟线程完成:对每个测量值的 200 毫秒等待不会阻塞任何系统线程;
  • 第 11–14 行:每个测量值一产生就被处理:每 200 毫秒一个(结果的第 2–5 行)。流在带资源的 [try] 中声明:关闭它会触发 [onClose] 动作(第 6 行);
  • 第 16–27 行:为了在循环结束之前退出,使用流的迭代器来遍历流。在 [break] 之后,生产者不会产生剩余的 96 个测量值,并且流在退出 [try] 时关闭(第 11 行)。[takeWhile] (Java 9)或 [limit] 方法也可以让你停止流;
  • 第 29–38 行:取消。该流由另一个虚拟线程读取,[waitForEnd] 方法(第 64–73 行)在 700 毫秒后中断它。对第四个测量值的等待被中断:[sleep] 方法抛出一个 [CancellationException],它穿过整个流;带资源的 [try] 关闭流(结果的第 15 行),然后 [catch] 报告取消(第 16 行);
  • 第 40–49 行:Stream API 能做的一切都可以应用于该流:过滤、转换、收集。结果只有在流结束时才可用,即 6 × 200 毫秒之后;
  • 第 90–96 行:[toString] 方法在 [Measurement] 记录中被重新定义,以获得更紧凑的显示;[NumberFormat.getInstance()] 按照机器的语言格式化实数,不带多余的小数位([21]、[21.75])。

同样的模式也适用于 [BufferedReader] (它的行是按需读取的,其 [lines()] 方法返回一个 [Stream<String>])、[ResultSet]、JDBC,或套接字的输入流:在虚拟线程上,阻塞流就是异步流。

9.9.2. 推送模型:Flow 和 SubmissionPublisher

[java.util.concurrent.Flow] 接口(Java 9)把四个内部接口组合在一起,使响应式流标准化:

  • [Flow.Publisher<T>],发布者,产生值;通过其方法 [subscribe] 向它添加订阅者;
  • [Flow.Subscriber<T>],订阅者,通过其方法 [onNext] 接收值,通过 [onComplete] 接收流的结束,通过 [onError] 接收错误,并在开始时通过 [Flow.Subscription] 对象,经由 [onSubscribe] 与发布者相连;
  • [Flow.Subscription],订阅:[request(n)] 请求来自 [n] 的额外值,而 [cancel()] 终止订阅。发布者发送的值绝不会超过订阅者所请求的数量:这就是“背压”(backpressure),它能防止快速的发布者压垮缓慢的订阅者;
  • [Flow.Processor<T, R>] 既是订阅者又是发布者(一个转换节点)。

Java 提供了发布者的一个实现 [SubmissionPublisher<T>],它通过执行器和每个订阅者专属的缓冲区向各个订阅者交付值。响应式库(Project Reactor、RxJava)实现了这些相同的接口,并为其添加了数十种运算符。程序 [Async20.java] 向两个订阅者发布六个测量值:一个快速的显示器,在温度超过 22 °C 时取消订阅;以及一个缓慢的归档器:

// “推送”模型:java.util.concurrent.Flow 和 SubmissionPublisher(Java 9)
final long start = System.nanoTime();

void main() throws InterruptedException {
    Subscriber screen = new Subscriber("screen", 0, 22);
    Subscriber archive = new Subscriber("archive", 500, Double.MAX_VALUE);
    // 发布者将值的投递交给执行器,并为每个订阅者保留 2 个值的缓冲区
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        var publisher = new SubmissionPublisher<Measurement>(executor, 2);
        publisher.subscribe(screen);
        publisher.subscribe(archive);
        for (int i = 1; i <= 6; i++) {
            sleep(200);
            // 如果订阅者的缓冲区没有空位,submit 会等待;它返回估计的滞后量
            int lag = publisher.submit(new Measurement("sensor-1", i, 19.5 + i * 0.75));
            display("publisher: measurement no. " + i + " published, estimated lag: " + lag);
        }
        // close() 向订阅者发出流结束的信号:它们的 onComplete 方法将被调用
        display("publisher: end of publication");
        publisher.close();
        // 我们等待归档处理完所有内容
        archive.end.await();
    }
}

// 一个订阅者,处理每次测量耗时 [duration] 毫秒,并在超过 [threshold] 后取消订阅
class Subscriber implements Flow.Subscriber<Measurement> {
    private final String name;
    private final long duration;
    private final double threshold;
    private Flow.Subscription subscription;
    final CountDownLatch end = new CountDownLatch(1);

    Subscriber(String name, long duration, double threshold) {
        this.name = name;
        this.duration = duration;
        this.threshold = threshold;
    }

    @Override
    public void onSubscribe(Flow.Subscription subscription) {
        this.subscription = subscription;
        // 订阅者逐个请求值:由它来控制速率
        subscription.request(1);
    }

    @Override
    public void onNext(Measurement measurement) {
        display("  " + name + " : received " + measurement);
        sleep(duration);
        if (measurement.value() >= threshold) {
            display("  " + name + " : threshold reached, unsubscribing");
            subscription.cancel();
        } else {
            subscription.request(1);
        }
    }

    @Override
    public void onError(Throwable e) {
        display("  " + name + " : error " + e);
        end.countDown();
    }

    @Override
    public void onComplete() {
        display("  " + name + " : end of the stream");
        end.countDown();
    }
}

// 没有受检异常的 Thread.sleep:中断会变成 CancellationException
void sleep(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new CancellationException("wait interrupted");
    }
}

// 显示自开始以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

// 一次测量
record Measurement(String sensor, int number, double value) {
    @Override
    public String toString() {
        return sensor + " no. " + number + " : " + NumberFormat.getInstance().format(value) + " °C";
    }
}

结果:

> java Async20.java
  221 ms : publisher: measurement no. 1 published, estimated lag: 1
  269 ms :   archive : received sensor-1 no. 1 : 20.25 °C
  274 ms :   screen : received sensor-1 no. 1 : 20.25 °C
  466 ms : publisher: measurement no. 2 published, estimated lag: 2
  466 ms :   screen : received sensor-1 no. 2 : 21 °C
  667 ms :   screen : received sensor-1 no. 3 : 21.75 °C
  667 ms : publisher: measurement no. 3 published, estimated lag: 3
  770 ms :   archive : received sensor-1 no. 2 : 21 °C
  867 ms : publisher: measurement no. 4 published, estimated lag: 3
  868 ms :   screen : received sensor-1 no. 4 : 22.5 °C
  868 ms :   screen : threshold reached, unsubscribing
 1271 ms :   archive : received sensor-1 no. 3 : 21.75 °C
 1271 ms : publisher: measurement no. 5 published, estimated lag: 3
 1771 ms :   archive : received sensor-1 no. 4 : 22.5 °C
 1772 ms : publisher: measurement no. 6 published, estimated lag: 3
 1772 ms : publisher: end of publication
 2274 ms :   archive : received sensor-1 no. 5 : 23.25 °C
 2775 ms :   archive : received sensor-1 no. 6 : 24 °C
 3276 ms :   archive : end of the stream

说明:

  • 第 26–70 行:订阅者,它用 [duration] 毫秒处理每个测量值,并在测量值达到 [threshold] 时取消订阅:
    • 第 40–45 行:[onSubscribe] 接收订阅并请求第一个值;
    • 第 47–57 行:[onNext] 处理一个值,然后要么请求另一个值([request(1)]),要么终止订阅([cancel()])。通过一次请求一个值,订阅者自己控制数据速率;
    • 第 59–69 行:[onError] 和 [onComplete] 表示流的结束,分别对应出错和正常结束。[CountDownLatch] 使主程序可以等待这一结束;
  • 第 9 行:发布者通过指定执行器的任务向每个订阅者交付值——这里是虚拟线程(如果没有执行器,它会使用共享池,而等待归档器会阻塞其为数不多的线程之一)——并为每个订阅者维护一个最多容纳 2 个值的缓冲区;
  • 第 12–17 行:发布者使用 [submit] 每 200 毫秒发布一个测量值,它返回对延迟的一个估计值:已发布但尚未被某个订阅者消费的值的最大数量。当某个订阅者的缓冲区已满时,[submit] 会等待空位出现:在大约 1,070 毫秒时就绪的 5 号测量值,直到 1,271 毫秒才被发布(结果的第 14 行),此时归档器已处理完 3 号测量值。这就是背压:发布者被减慢到最慢订阅者的节奏。([SubmissionPublisher] 还提供 [offer],它允许丢弃一个值而不是等待);
  • 结果显示,速度很快的显示器在每个测量值一发布就处理它,并在 4 号测量值(22.5 °C,第 11–12 行)时取消订阅,而每个测量值需要 500 毫秒的归档器则落在后面,并收到了全部六个测量值;
  • 第 18–22 行:[close()] 表示流的结束:每个仍处于订阅状态的订阅者在处理完其缓冲区中的值之后,都会收到 [onComplete] (第 20 行)。程序通过 [CountDownLatch] 消息等待归档器结束。

推送模型适用于按自身节奏产生数据的来源(传感器、事件、消息)以及响应式处理链;拉取模型编写和阅读起来更简单,适用于按需从来源读取。使用虚拟线程时,拉取模型通常就足够了。

9.10. 缓存、切回正确的线程,以及自行结束操作

9.10.1. 异步操作的缓存

[CompletableFuture] 是一个对象:每次调用返回它的方法,都会在堆上至少分配一个对象,垃圾回收器必须回收它。对于持续几毫秒的 I/O 来说,这可以忽略不计,而且 JVM 中当前的垃圾回收器能非常高效地处理短命对象:Java 没有 [CompletableFuture] 的“轻量”变体(其他语言有,用于被调用数百万次、且大多数情况下已经有结果的异步方法)。

对于经常已经有结果的异步方法,最佳实践是缓存 [CompletableFuture] 对象本身:已知的值由一个已完成的 [CompletableFuture] 返回,无需新的分配,而且对同一个值的多个并发请求共享同一个正在进行的操作。[Async21.java] 程序把这一做法应用于汇率服务:

// CompletableFuture 缓存:一个大多数时候已有结果的异步操作
void main() {
    var service = new RateService();
    // 1 - 连续读取:只有对某种货币的第一次读取会查询服务器
    for (String code : List.of("EUR", "USD", "EUR", "EUR", "USD", "GBP", "EUR")) {
        long readingStart = System.nanoTime();
        BigDecimal rate = service.readRate(code).join();
        IO.println(String.format("%s : %6s read in %3d ms", code, NumberFormat.getInstance().format(rate),
                (System.nanoTime() - readingStart) / 1_000_000));
    }
    IO.println("1 - server accesses: " + service.nbServerAccesses() + ", readings: " + service.nbReadings());

    // 2 - 对同一种货币的三次同时读取:它们共享同一个操作
    List<CompletableFuture<BigDecimal>> readings = List.of(
            service.readRate("CHF"), service.readRate("CHF"), service.readRate("CHF"));
    IO.println("2 - same object: " + (readings.get(0) == readings.get(2))
            + ", rate: " + NumberFormat.getInstance().format(readings.get(0).join())
            + ", server accesses: " + service.nbServerAccesses() + ", readings: " + service.nbReadings());

    // 3 - 失败的操作不会保留在缓存中
    try {
        service.readRate("XYZ").join();
    } catch (CompletionException e) {
        IO.println("3 - " + e.getCause().getMessage() + ", cached currencies: " + service.cachedCurrencies());
    }
}

class RateService {
    // 缓存包含 CompletableFuture 本身,已完成的或进行中的
    private final Map<String, CompletableFuture<BigDecimal>> cache = new ConcurrentHashMap<>();
    private final AtomicInteger nbServerAccesses = new AtomicInteger();
    private final AtomicInteger nbReadings = new AtomicInteger();

    CompletableFuture<BigDecimal> readRate(String code) {
        nbReadings.incrementAndGet();
        // 如果货币在缓存中,我们返回已有的 CompletableFuture:不创建对象
        return cache.computeIfAbsent(code, this::readRateFromServer);
    }

    private CompletableFuture<BigDecimal> readRateFromServer(String code) {
        nbServerAccesses.incrementAndGet();
        // 模拟查询远程服务器(300 毫秒)
        CompletableFuture<BigDecimal> reading = new CompletableFuture<Void>()
                .completeOnTimeout(null, 300, TimeUnit.MILLISECONDS)
                .thenApply(nothing -> switch (code) {
                    case "EUR" -> BigDecimal.ONE;
                    case "USD" -> new BigDecimal("1.17");
                    case "GBP" -> new BigDecimal("0.87");
                    case "CHF" -> new BigDecimal("0.94");
                    default -> throw new IllegalArgumentException("unknown currency: " + code);
                });
        // 失败时,我们从缓存中移除该操作,以便以后的读取重试
        return reading.whenComplete((rate, e) -> {
            if (e != null) {
                cache.remove(code);
            }
        });
    }

    int nbServerAccesses() {
        return nbServerAccesses.get();
    }

    int nbReadings() {
        return nbReadings.get();
    }

    Set<String> cachedCurrencies() {
        return new TreeSet<>(cache.keySet());
    }
}

结果:

> java Async21.java
EUR :      1 read in 363 ms
USD :   1.17 read in 300 ms
EUR :      1 read in   0 ms
EUR :      1 read in   0 ms
USD :   1.17 read in   0 ms
GBP :   0.87 read in 300 ms
EUR :      1 read in   0 ms
1 - server accesses: 3, readings: 7
2 - same object: true, rate: 0.94, server accesses: 4, readings: 10
3 - unknown currency: XYZ, cached currencies: [CHF, EUR, GBP, USD]

说明:

  • 第 30 行:缓存把每个货币代码与其汇率的 [CompletableFuture] 关联起来,无论该操作已完成还是仍在进行。这是一个 [ConcurrentHashMap] (第 8 章),因为它可能被多个线程同时使用(主线程、完成读取的定时器线程);
  • 第 34–38 行:如果键存在,[computeIfAbsent(key, function)] 返回与该键关联的值;否则,它调用该函数,把结果存入字典并返回。对于 [ConcurrentHashMap],这个操作是原子的:两个同时请求某个不存在的货币的线程只会触发一次对服务器的访问;
  • 第 40–58 行:模拟的服务器查询(300 毫秒)。后续操作 [thenApply] 包含一个针对字符串的 [switch] 表达式,其分支 [default] 会为未知货币抛出异常;
  • 第 52–57 行:失败时,该操作会从缓存中移除,这样后续对同一货币的请求会再次查询服务器,而不是无限期地返回同一个失败。存入缓存的是 [CompletableFuture] ,由 [whenComplete] 返回:它要等到该动作执行完毕后才完成,这向调用者保证:当它收到结果时,缓存已是最新的;
  • 第 5–11 行:对调用者来说,什么都没有改变:它用 [join()] 等待结果。结果显示了三次服务器访问(每次 300 毫秒;第一次稍长,因为 JVM 在此期间加载必要的类)和四次来自缓存的即时响应;
  • 第 13–18 行:对瑞士法郎汇率的三个同时请求获取的是同一个对象,并且只导致一次服务器访问(结果的第 10 行);
  • 第 20–25 行:未知货币导致了失败,并且不再留在缓存中(第 11 行)。

9.10.2. 返回 GUI 线程

程序 [Async06.java] 演示了后续操作视情况由完成操作的线程或所选执行器的线程来执行。在图形应用程序(Swing、JavaFX)中,这很重要:图形组件只能由 UI 线程操作。Java 没有自动把其余代码交回这个线程的机制;需要由程序来请求,要么向后续操作传入正确的执行器,要么使用图形库的工具:

  • 在 Swing 中,*[SwingUtilities.invokeLater(action)] 会让动作由界面线程执行;方法引用 [SwingUtilities::invokeLater] 可以充当后续操作的执行器:[download.thenAcceptAsync(page -> textArea.setText(page), SwingUtilities::invokeLater)]******。[SwingWorker] 类还提供一个由后台线程执行的方法 [doInBackground],以及由界面线程执行的方法 [process] 和 [done]*;
  • 在 JavaFX 中,[Platform.runLater(action)] 起同样的作用,而 [Task] 和 [Service] 这两个 [javafx.concurrent] 中的类把后台过程及其进度封装在一起。

无论哪种情况,规则都是一样的:UI 线程绝不能等待([join()]、[get()]、阻塞 I/O),否则窗口就会冻结。耗时的任务由另一个线程(例如虚拟线程)执行,只有组件的最终更新由界面线程处理。

9.10.3. 手动终结 CompletableFuture

有时你可能需要使用一个通过监听器(第 7 章)发出事件信号的 API,而其余代码是使用 [CompletableFuture] 编写的。我们在 [Async17.java] 中见过这种技术:使用其构造函数创建一个“待定”的 [CompletableFuture] ,立即返回它,并在需要时自行终结它:

  • [complete(value)] 使它成功完成;
  • [completeExceptionally(exception)] 使它以失败告终;
  • [cancel(false)] 取消它。

如果 [CompletableFuture] 已经完成,这三个方法就不起作用([complete] 和 [completeExceptionally] 此时会产生 [false]):第一个完成它的获胜,这自然解决了竞争情形(例如结果和超时同时到达)。程序 [Async22.java] 等待一个温度计——它在每次测量时通知其监听器——达到某个温度:

// “手动”完成的 CompletableFuture:将基于监听器的 API 转换为异步操作
final long start = System.nanoTime();

void main() {
    var thermometer = new Thermometer();
    thermometer.start();

    // 1 - 我们等待第一个大于或等于 21 °C 的测量值
    double measure = waitForTemperature(thermometer, 21).join();
    display("1 - temperature reached: " + format(measure) + " °C");

    // 2 - 同样的等待,限时一秒
    try {
        measure = waitForTemperature(thermometer, 30).orTimeout(1, TimeUnit.SECONDS).join();
        display("2 - temperature reached: " + format(measure) + " °C");
    } catch (CompletionException e) {
        display("2 - 30 °C not reached in one second: " + e.getCause().getClass().getSimpleName());
    }
    thermometer.stop();
}

// 将温度计的通知转换为 CompletableFuture
CompletableFuture<Double> waitForTemperature(Thermometer thermometer, double threshold) {
    // 一个由我们自己来完成的 CompletableFuture
    CompletableFuture<Double> result = new CompletableFuture<>();
    // 达到阈值时,监听器完成该 CompletableFuture
    DoubleConsumer listener = temperature -> {
        if (temperature >= threshold) {
            result.complete(temperature);
        }
    };
    thermometer.addListener(listener);
    // 无论以何种方式结束(阈值、超时、取消),我们都移除监听器
    result.whenComplete((temperature, e) -> thermometer.removeListener(listener));
    // CompletableFuture 立即返回;它将在稍后完成
    return result;
}

// 一个每 200 毫秒通知其监听器的温度计(“老式”API)
class Thermometer {
    private final List<DoubleConsumer> listeners = new CopyOnWriteArrayList<>();
    private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
    private double temperature = 19;

    void addListener(DoubleConsumer listener) {
        listeners.add(listener);
    }

    void removeListener(DoubleConsumer listener) {
        listeners.remove(listener);
    }

    void start() {
        timer.scheduleAtFixedRate(() -> {
            temperature += 0.5;
            IO.println("          measure: " + format(temperature) + " °C");
            listeners.forEach(listener -> listener.accept(temperature));
        }, 200, 200, TimeUnit.MILLISECONDS);
    }

    void stop() {
        timer.shutdown();
    }
}

// 以本地格式表示的实数,不带多余的小数
String format(double value) {
    return NumberFormat.getInstance().format(value);
}

// 显示自开始以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

结果:

> java Async22.java
          measure: 19.5 °C
          measure: 20 °C
          measure: 20.5 °C
          measure: 21 °C
  807 ms : 1 - temperature reached: 21 °C
          measure: 21.5 °C
          measure: 22 °C
          measure: 22.5 °C
          measure: 23 °C
          measure: 23.5 °C
 1809 ms : 2 - 30 °C not reached in one second: TimeoutException

说明:

  • 第 39–64 行:温度计,一个“老派”的类:[ScheduledExecutorService] 每 200 毫秒把温度提高 0.5 °C,并把它传给其监听器,监听器的类型为 [DoubleConsumer](一种专用于 [Consumer] 的 [double] 类型的接口)。监听器列表是一个 [CopyOnWriteArrayList],即可以在一个线程修改它(添加或移除监听器)的同时由另一个线程遍历的列表;
  • 第 22–37 行:把通知转换为一个 [CompletableFuture] 的方法。它创建一个临时的 [CompletableFuture<Double>],向温度计注册一个监听器,并立即返回尚未完成的 [CompletableFuture];
  • 第 27–31 行:每次测量时,监听器都检查阈值。达到阈值时,它以该温度作为结果终结 [CompletableFuture] 。此后的测量继续调用 [complete],但没有任何效果,直到监听器被移除;
  • 第 34 行:无论 [CompletableFuture] 如何结束(达到阈值、超时、被调用者取消),[whenComplete] 都会移除监听器。否则,永远达不到阈值的监听器会一直保持注册;
  • 第 8–18 行:对调用者来说,等待某个温度和其他任何异步操作一样:调用者用 [join()] 等待它,并用 [orTimeout] 为它设置时限。由于 [orTimeout] 终结的是 [CompletableFuture] 本身(而不是它的副本),第 34 行的动作 [whenComplete] 会被执行,监听器也就被移除了。

需要提醒的是:附加到 [CompletableFuture] 上的后续操作由调用 [complete] 的线程执行——这里是温度计线程——并且是在它通知监听器的过程中。如果这些后续操作很耗时,就应该使用 [xxxAsync] 变体和执行器来编写,或者应该用 [CompletableFuture] 通过 [completeAsync(() -> value, executor)](Java 9)终结,这会让执行器去调用 [complete]。

9.11. 有限的并行度

9.11.1. 虚拟线程与信号量

[allOf] 加上每个操作一个虚拟线程,会同时启动所有操作。这并不总是我们想要的:要下载 10,000 个网页,你不会希望向同一台服务器同时打开 10,000 个连接。对于平台线程,并发度受线程池大小限制。而对于虚拟线程,线程不池化(它们的开销非常小,每个任务创建一个):对稀缺资源的访问通过 [Semaphore] (第 8 章)来限制,其许可数表示允许的并发操作数。程序 [Async23.java] 下载九个页面,每次最多三个:

// 用有限数量的同时操作处理集合:虚拟线程和 Semaphore
final AtomicInteger inProgress = new AtomicInteger();

long start;

void main() {
    start = System.nanoTime();
    List<String> pages = IntStream.rangeClosed(1, 9).mapToObj(i -> "page" + i + ".html").toList();
    // 同一时间最多 3 个下载:一个有 3 个许可的信号量
    var permits = new Semaphore(3);
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        // 每个页面一个虚拟线程:它们开销很小,页面有多少就可以创建多少
        for (String page : pages) {
            executor.submit(() -> {
                // 线程等待一个许可(不会阻塞载体线程)
                permits.acquire();
                try {
                    download(page);
                } finally {
                    permits.release();
                }
                return null;
            });
        }
    } // close() 等待所有下载结束
    display("the " + pages.size() + " pages are downloaded");
}

void download(String page) throws InterruptedException {
    // 同时进行的操作共享的计数器:我们以原子方式修改它
    int n = inProgress.incrementAndGet();
    display("start of " + page + " (" + n + " in progress)");
    // 模拟页面下载
    Thread.sleep(1000);
    inProgress.decrementAndGet();
    display("end of " + page);
}

// 显示自开始以来经过的时间以及执行该显示的线程
void display(String message) {
    Thread thread = Thread.currentThread();
    String name = thread.isVirtual() ? "virtual #" + thread.threadId() : thread.getName();
    IO.println(String.format("%5d ms [%-11s] : %s", (System.nanoTime() - start) / 1_000_000, name, message));
}

结果:

> java Async23.java
   13 ms [virtual #25] : start of page2.html (2 in progress)
   13 ms [virtual #27] : start of page3.html (3 in progress)
   13 ms [virtual #23] : start of page1.html (1 in progress)
 1026 ms [virtual #25] : end of page2.html
 1026 ms [virtual #27] : end of page3.html
 1026 ms [virtual #23] : end of page1.html
 1026 ms [virtual #28] : start of page4.html (1 in progress)
 1027 ms [virtual #29] : start of page5.html (2 in progress)
 1027 ms [virtual #30] : start of page6.html (3 in progress)
 2027 ms [virtual #29] : end of page5.html
 2027 ms [virtual #30] : end of page6.html
 2028 ms [virtual #31] : start of page7.html (1 in progress)
 2028 ms [virtual #32] : start of page8.html (2 in progress)
 2027 ms [virtual #28] : end of page4.html
 2028 ms [virtual #33] : start of page9.html (3 in progress)
 3028 ms [virtual #31] : end of page7.html
 3028 ms [virtual #32] : end of page8.html
 3029 ms [virtual #33] : end of page9.html
 3030 ms [main       ] : the 9 pages are downloaded

说明:

  • 第 10 行:一个有 3 个许可的信号量;
  • 第 13–24 行:每个页面一个虚拟线程。任务是一个以 [return null;] 结尾的 lambda:因此它是一个 [Callable],其方法可以抛出受检异常,这样在这里就不必处理 [InterruptedException]、[acquire] 和 [Thread.sleep] ;
  • 第 16–21 行:每个线程等待一个许可([acquire]),下载其页面,然后在 [release] 的 [finally] 中归还许可,这样即使下载失败也会归还。等待授权的虚拟线程会从其宿主线程上分离,就像在 I/O 操作期间一样;
  • 第 29–37 行:计数器 [inProgress] 由各线程共享,是以原子方式修改的 [AtomicInteger];
  • 结果显示三波、每波三个页面:一个页面一结束,另一个就开始,而且正在进行的下载数从未超过 3。整个过程耗时 3 秒,而不是 9 秒。当两个线程几乎同时写入时,各行的顺序在不同执行之间可能有所不同,显示的时间甚至可能比上一行稍早;
  • 每个页面都有自己的虚拟线程(编号 23 到 33;这些编号由 JVM 中的所有线程共享,包括载体线程,因此有空缺),但这九个虚拟线程是由机器上仅有的两个载体线程执行的。

9.11.2. 生产者 / 消费者:BlockingQueue

上一章介绍了生产者/消费者模型:生产者把条目放入队列,消费者把它们取出。[BlockingQueue<E>] 接口就是用于此目的的工具:[put] 把一个条目放入队列,并且如果队列有界且已满,就等待空位出现;[take] 移除一个元素,并且如果队列为空,就等待元素到来;[offer] 和 [poll] 尝试做同样的事,但不等待(或只等待一段时间)。这些等待是阻塞的;由虚拟线程执行时,它们不会阻塞任何系统线程,阻塞队列就成为异步操作之间的通信工具。

程序 [Async24.java] 有每 50 毫秒生成一次的命令,由两个消费者处理,每个消费者处理一条命令需要 400 毫秒:

// 使用阻塞队列的生产者 / 消费者,由虚拟线程执行
// 向消费者表示不会再有订单的值
static final int END = -1;
// 有界队列:最多容纳 2 个等待处理的订单
final BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
long start;

void main() {
    start = System.nanoTime();
    // 生产者和两个消费者同时工作
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        executor.submit(() -> produce(8));
        executor.submit(() -> consume("C1"));
        executor.submit(() -> consume("C2"));
    }
    display("all the orders have been processed");
}

// 生产者:每 50 毫秒一个订单
Void produce(int nbOrders) throws InterruptedException {
    for (int i = 1; i <= nbOrders; i++) {
        Thread.sleep(50);
        // 如果队列中有空位,offer 立即放入订单
        if (queue.offer(i)) {
            display("P  : order " + i + " queued");
        } else {
            // 队列已满:put 等待有空位腾出
            display("P  : queue full, order " + i + " waits");
            queue.put(i);
            display("P  : order " + i + " queued");
        }
    }
    // 不会再有产出:我们放入结束标记
    queue.put(END);
    display("P  : end of production");
    return null;
}

// 消费者:处理一个订单需要 400 毫秒
Void consume(String name) throws InterruptedException {
    while (true) {
        // take 等待直到队列中有订单
        int order = queue.take();
        if (order == END) {
            // 我们把结束标记放回队列,供另一个消费者使用
            queue.put(END);
            break;
        }
        display(name + " : processing of order " + order);
        Thread.sleep(400);
    }
    display(name + " : no more orders");
    return null;
}

// 显示自开始以来经过的时间
void display(String message) {
    IO.println(String.format("%5d ms : %s", (System.nanoTime() - start) / 1_000_000, message));
}

结果:

> java Async24.java
   58 ms : P  : order 1 queued
   62 ms : C1 : processing of order 1
  118 ms : C2 : processing of order 2
  119 ms : P  : order 2 queued
  169 ms : P  : order 3 queued
  220 ms : P  : order 4 queued
  271 ms : P  : queue full, order 5 waits
  469 ms : P  : order 5 queued
  469 ms : C1 : processing of order 3
  519 ms : C2 : processing of order 4
  519 ms : P  : order 6 queued
  570 ms : P  : queue full, order 7 waits
  870 ms : C1 : processing of order 5
  870 ms : P  : order 7 queued
  920 ms : C2 : processing of order 6
  920 ms : P  : order 8 queued
 1270 ms : C1 : processing of order 7
 1271 ms : P  : end of production
 1320 ms : C2 : processing of order 8
 1672 ms : C1 : no more orders
 1721 ms : C2 : no more orders
 1721 ms : all the orders have been processed

说明:

  • 第 5 行:一个容量为 2 的 [ArrayBlockingQueue] :它最多包含 2 条待处理的命令;
  • 第 11–15 行:生产者和两个消费者由三个虚拟线程执行;程序使用执行器的 [close()] 方法等待这三个线程全部结束。方法 [produce] 和 [consume] 返回 [Void] 并以 [return null;] 结尾:因此第 12–14 行的 lambda 是 [Callable],这些方法可以声明 [InterruptedException];
  • 第 19–37 行:生产者尝试使用 [offer] 提交每个订单。如果队列已满,它会发出信号,并使用 [put] 等待空位:生产者被限制在消费者的节奏上(结果的第 8–9 行)。这就是有界队列的好处:过快的生产者无法占满内存;
  • 第 34 行:生产完成;生产者放入一个特定的值,即结束标记 [END] (第 3 行),消费者会识别它。事实上,阻塞队列没有办法表示它已“关闭”;
  • 第 39–54 行:每个消费者使用 [take] 取出订单。一个订单只会交给一个消费者:订单根据 C1 和 C2 的空闲情况在它们之间分配。收到结束令牌的消费者把它放回队列供另一个消费者使用,然后停止;
  • 与前一个示例一样,几乎同时显示的两行可能会乱序出现。

9.12. 时间:ScheduledExecutorService 和 Clock

有两个工具与时间相关的工具互为补充:

  • [ScheduledExecutorService] (Java 5)是一个能够在延迟之后([schedule])或周期性地([scheduleAtFixedRate],按固定间隔,从一次执行的开始到下一次执行的开始计时;[scheduleWithFixedDelay],在一次执行的结束与下一次执行的开始之间采用固定延迟)运行任务的执行器。周期性任务绝不会同时执行两次:如果某次执行耗时超过周期,下一次执行就会被推迟。单线程的执行器可以通过 [Executors.newSingleThreadScheduledExecutor()] 获得;
  • 抽象类 [java.time.Clock] (Java 8)表示时钟:它提供当前时间和时区。[Clock.systemDefaultZone()] 是使用机器时区的系统时钟。API [now()] 的所有方法、[java.time] ([LocalDateTime.now(clock)]、[Instant.now(clock)]……)都接受一个时钟。依赖时间的类接收一个 [Clock] ,而不是调用 [LocalDateTime.now()]:这样就可以用受控的时钟对其进行测试。

程序 [Async25.java] 同时使用了这两者:

// 时间:ScheduledExecutorService 和 Clock
void main() throws InterruptedException {
    // 1 - 每 500 毫秒一个动作,2.2 秒后停止
    long start = System.nanoTime();
    AtomicInteger nbTicks = new AtomicInteger();
    try (ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor()) {
        // scheduleAtFixedRate:500 毫秒后第一次触发,然后每 500 毫秒触发一次
        ScheduledFuture<?> ticks = scheduler.scheduleAtFixedRate(
                () -> IO.println(String.format("%6d ms : tick no. %d",
                        (System.nanoTime() - start) / 1_000_000, nbTicks.incrementAndGet())),
                500, 500, TimeUnit.MILLISECONDS);
        // schedule:一个单次动作,在 2.2 秒后停止触发
        ScheduledFuture<?> stop = scheduler.schedule(
                () -> ticks.cancel(false), 2200, TimeUnit.MILLISECONDS);
        stop.get();
        IO.println(String.format("%6d ms : timer stopped after %d ticks",
                (System.nanoTime() - start) / 1_000_000, nbTicks.get()));
    } catch (ExecutionException e) {
        IO.println("error: " + e.getCause());
    }

    // 2 - Clock:依赖时间的类接收其时钟,而不是调用 LocalDateTime.now()
    Clock morning = Clock.fixed(Instant.parse("2026-10-03T09:30:00Z"), ZoneOffset.UTC);
    Clock evening = Clock.fixed(Instant.parse("2026-10-03T19:45:00Z"), ZoneOffset.UTC);
    IO.println(new Reception(morning).greet("Pierre"));
    IO.println(new Reception(evening).greet("Pierre"));
    IO.println(new Reception(Clock.systemDefaultZone()).greet("Pierre") + " (system clock)");
}

// 依赖当前时间的类
record Reception(Clock clock) {
    String greet(String name) {
        LocalDateTime now = LocalDateTime.now(clock);
        String greeting = now.getHour() < 18 ? "Hello" : "Good evening";
        String date = now.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));
        return "[" + date + "] " + greeting + " " + name;
    }
}

结果:

1
2
3
4
5
6
7
8
9
> java Async25.java
   504 ms : tick no. 1
  1003 ms : tick no. 2
  1503 ms : tick no. 3
  2003 ms : tick no. 4
  2204 ms : timer stopped after 4 ticks
[03/10/2026 09:30] Hello Pierre
[03/10/2026 19:45] Good evening Pierre
[03/10/2026 19:18] Good evening Pierre (system clock)

说明:

  • 第 8–11 行:[scheduleAtFixedRate(task, initialDelay, period, unit)] 在 500 毫秒后首次运行任务,此后每 500 毫秒运行一次。它返回一个 [ScheduledFuture] 和一个 [Future],除其他用途外,它还允许取消以后的执行。计时计数器是一个 [AtomicInteger]:lambda 不能修改局部变量;
  • 第 13–15 行:[schedule(task, delay, unit)] 在 2.2 秒后执行一个一次性任务:它取消计时。[stop.get()] 等待该任务结束。蜂鸣声出现在 0.5、1、1.5 和 2 秒时,计时器在 2.2 秒时停止,共响了 4 声;
  • 第 30–38 行:记录 [Reception] 根据时间说“Hello”或“Good evening”。它从构造函数接收时钟,而不是调用 [LocalDateTime.now()]:这是一个被注入的依赖,就像第 6 章中 [dao] 层被注入到 [business] 层一样;
  • 第 23–27 行:[Clock.fixed(instant, zone)] 返回一个始终显示同一时间的静止时钟;这使我们无需等到晚上,就能验证 [Reception] 在早上和晚上的行为。最后一行使用系统时钟(因此结果取决于执行时间)。对于更复杂的测试,你可以编写自己的、派生自 [Clock] 的类,并按需推进它。[InstantSource] 接口(Java 17)只返回当前时间,当时区无关紧要时,它是更轻量的依赖。

要测量时长,不要使用时钟(它在测量期间可能被调整,例如通过同步系统时间),而应使用 [System.nanoTime()],如本章的示例所示。

9.13. 结构化并发(概述)

在前面的示例中,程序启动的操作独立于它运行:如果其中一个失败,其他的会继续;如果启动它们的代码被中断,它们同样会继续;而且没有任何机制强制该代码等待它们结束。结构化并发提议把一组子任务视为单个块:它们在一个作用域内启动,作用域等待它们完成,如果其中一个失败,其他的就会被取消。[StructuredTaskScope] 类使用虚拟线程实现了这一思想。它自 Java 21 起就已提供,但在 Java 25 中仍处于“预览”状态:其 API 仍可能改变,使用它的程序必须带 [--enable-preview] 选项编译和运行。因此它不包含在课程练习中;下面的代码(文件 [preview/StructuredConcurrency.txt],要测试它,需将其复制到名为 [StructuredConcurrency.java] 的文件中)可以让你大致了解它的工作方式:

// 结构化并发:Java 25 中的预览 API
// 执行:java --enable-preview StructuredConcurrency.java
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;

void main() throws InterruptedException {
    // 1 - 两个必须都成功的子任务
    try (var scope = StructuredTaskScope.open()) {
        Subtask<Integer> angers = scope.fork(() -> readTemperature("Angers", 1000));
        Subtask<Integer> brest = scope.fork(() -> readTemperature("Brest", 500));
        // join 等待子任务结束;如果其中一个失败,另一个被取消
        // 并且 join 抛出异常
        scope.join();
        IO.println("Angers: " + angers.get() + ", Brest: " + brest.get());
    }
    // 2 - 第一个回答就够了:其他子任务被取消
    try (var scope = StructuredTaskScope.open(Joiner.<Integer>anySuccessfulResultOrThrow())) {
        scope.fork(() -> readTemperature("mirror-paris", 800));
        scope.fork(() -> readTemperature("mirror-lyon", 300));
        IO.println("first answer: " + scope.join());
    }
}

int readTemperature(String city, long duration) throws InterruptedException {
    Thread.sleep(duration);
    return 10 + city.length();
}

结果:

1
2
3
> java --enable-preview StructuredConcurrency.java
Angers: 16, Brest: 15
first answer: 21

说明:

  • 第 8 行:[StructuredTaskScope.open()] 打开一个作用域,它在带资源的 [try] 中声明;关闭它可确保没有子任务比它存活得更久;
  • 第 9–10 行:[fork] 在新的虚拟线程中启动一个子任务,并返回一个 [Subtask];
  • 第 13 行:[join()] 等待所有子任务结束。在默认策略下,如果某个子任务失败,其他子任务会被取消(中止),并且 [join()] 会抛出异常;
  • 第 14 行:子任务的结果,所有子任务均已完成;
  • 第 17–21 行:由 [Joiner] 提供的另一种策略:第一个成功的子任务返回 [join()] 的结果,其他子任务被取消。这是 [anyOf] 的结构化等价物,但落败的请求会被真正终止。

9.14. 应用:使用虚拟线程计算税款

程序 [Async26.java] 把本章中与主线程的税款计算相关的几种工具结合在一起。它从已经使用过的文件 [TaxData.txt] 中读取税率档,并从文件 [taxpayers.txt] 中读取纳税人列表:

1
2
3
4
5
6
7
y 2 60000
y 3 60000
n 0 60000
n 2 25000
y 5 120000
x 1 20000
y 1 -5

(每行包含:已婚与否 [y/n]、子女数、年薪),计算每个人的税款,并把结果写入文件 [results.txt]。两次读取由虚拟线程并发执行,整个过程限制在 10 秒内。

// 应用:税款计算,输入 / 输出由虚拟线程执行
// - 税率档从 [TaxData.txt] 读取,纳税人从 [taxpayers.txt] 读取
// - 结果写入 [results.txt]
// 正确的纳税人行:已婚(y/n),子女数,年薪
static final Pattern TAXPAYER = Pattern.compile("([yn])\\s+(\\d+)\\s+(\\d+)");

void main() {
    Path results = Path.of("results.txt");
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        // 两个输入文件由两个虚拟线程同时读取
        Future<List<TaxBracket>> bracketsReading = executor.submit(
                () -> loadBrackets(Path.of("TaxData.txt")));
        Future<List<String>> taxpayersReading = executor.submit(
                () -> Files.readAllLines(Path.of("taxpayers.txt")));
        // 计算等待两次读取完成,然后写入结果
        Future<Integer> processing = executor.submit(
                () -> calculateTaxes(bracketsReading.get(), taxpayersReading.get(), results));
        try {
            // 整个处理限时 10 秒
            int nbResults = processing.get(10, TimeUnit.SECONDS);
            IO.println(nbResults + " lines written in [" + results + "] :");
            IO.print(Files.readString(results));
        } catch (TimeoutException e) {
            processing.cancel(true);
            IO.println("processing abandoned: timeout exceeded");
        }
    } catch (ExecutionException e) {
        // 读取的错误被包装了两次:一次由读取包装,一次由等待它的计算包装
        Throwable cause = e.getCause();
        while (cause instanceof ExecutionException) {
            cause = cause.getCause();
        }
        IO.println("error: " + cause.getClass().getSimpleName() + " : " + cause.getMessage());
    } catch (IOException | InterruptedException e) {
        IO.println("error: " + e.getClass().getSimpleName() + " : " + e.getMessage());
    }
}

// 读取税率档(limit:coeffR:coeffN,小数点)
List<TaxBracket> loadBrackets(Path file) throws IOException {
    try (Stream<String> lines = Files.lines(file)) {
        return lines.filter(line -> !line.isBlank()).map(TaxBracket::parse).toList();
    }
}

// 计算每个纳税人的税款并写入结果
int calculateTaxes(List<TaxBracket> brackets, List<String> taxpayers, Path output) throws IOException {
    try (BufferedWriter writer = Files.newBufferedWriter(output)) {
        for (String line : taxpayers) {
            Matcher fields = TAXPAYER.matcher(line.trim());
            String result = fields.matches()
                    ? "tax = " + calculateTax(brackets, fields.group(1).equals("y"),
                            Integer.parseInt(fields.group(2)), Integer.parseInt(fields.group(3))) + " €"
                    : "incorrect line";
            writer.write(String.format("%-12s : %s", line, result));
            writer.newLine();
        }
    }
    return taxpayers.size();
}

// 税款计算(2003 年收入适用的 2004 年税率表,为练习而保留)
int calculateTax(List<TaxBracket> brackets, boolean married, int nbChildren, int salary) {
    BigDecimal shares = BigDecimal.valueOf(nbChildren).divide(BigDecimal.TWO)
            .add(BigDecimal.valueOf(married ? 2 : 1));
    if (nbChildren >= 3) {
        shares = shares.add(new BigDecimal("0.5"));
    }
    BigDecimal income = new BigDecimal("0.72").multiply(BigDecimal.valueOf(salary));
    BigDecimal quotient = income.divide(shares, MathContext.DECIMAL64);
    // 限额超过家庭系数的第一个税率档,否则取最后一个
    TaxBracket bracket = brackets.stream()
            .filter(t -> quotient.compareTo(t.limit()) <= 0)
            .findFirst()
            .orElse(brackets.getLast());
    return bracket.coeffR().multiply(income).subtract(bracket.coeffN().multiply(shares)).intValue();
}

// 一个税率档
record TaxBracket(BigDecimal limit, BigDecimal coeffR, BigDecimal coeffN) {
    static TaxBracket parse(String line) {
        String[] fields = line.split(":");
        return new TaxBracket(new BigDecimal(fields[0]), new BigDecimal(fields[1]),
                new BigDecimal(fields[2]));
    }
}

结果:

1
2
3
4
5
6
7
8
9
> java Async26.java
7 lines written in [results.txt] :
y 2 60000    : tax = 4282 €
y 3 60000    : tax = 2959 €
n 0 60000    : tax = 11519 €
n 2 25000    : tax = 792 €
y 5 120000   : tax = 11109 €
x 1 20000    : incorrect line
y 1 -5       : incorrect line

同一个程序,在缺少文件 [TaxData.txt] 的文件夹中运行:

> java Async26.java
error: NoSuchFileException : TaxData.txt

说明:

  • 第 11–14 行:两个输入文件由两个虚拟线程使用标准的阻塞读取方法([Files.lines]、[Files.readAllLines])同时读取;
  • 第 16–17 行:计算是第三个任务,它首先使用 [get()] 等待两次读取完成。这些等待阻塞的是虚拟线程,不产生任何代价;
  • 第 18–26 行:主程序最多等待结果 10 秒。超过之后,它中止该过程(这会终止其虚拟线程)并报告错误;
  • 第 27–36 行:错误在主程序中的单一位置处理。读取错误(文件缺失、数字不正确)存储在与读取操作相关联的 [Future] 中;计算任务中的 [get()] 把它重新抛出为 [ExecutionException],它又成为计算任务的异常,并由主程序的 [get] 重新抛出为第二个 [ExecutionException]。第 30–32 行的循环会回溯到最初的原因(第二个结果)。这是相互依赖的任务的缺点;上一段所述的结构化并发将消除这个问题;
  • 第 39–44 行:读取税率档,使用跳过空行的 [Stream] ;
  • 第 46–60 行:处理纳税人。每一行都由第 5 行的正则表达式验证:一个 [y] 或一个 [n],后面是两个用空格分隔的正整数([\s+])。圆括号定义了三个分组,在 [matches()] 验证整行与表达式匹配之后,由 [group(1)]、[group(2)] 和 [group(3)] 返回它们。不正确的行([x] 而不是 [y/n],或薪水为负)会被标记为错误;
  • 第 62–77 行:税款计算,使用 [BigDecimal]。收入除以份数可能无法整除:这里以 16 位有效数字的精度进行([MathContext.DECIMAL64])。其阈值大于或等于家庭商数的第一个税率档由一个流确定;如果没有匹配的,[orElse(brackets.getLast())] 返回最后一个税率档。[intValue()] 把税款向下取整到整数欧元;
  • 结果提供了贯穿全程的校验值:已婚、有 2 个孩子、薪水为 60,000 欧元的夫妇税款为 4,282 欧元,有 3 个孩子时为 2,959 欧元,而无子女的单身者为 11,519 欧元。

计算本身是同步的:它不执行任何 I/O,只需几微秒。把它卸载到另一个线程是毫无意义的,甚至是有害的。只有涉及等待的任务才会被异步化。

9.15. 黄金法则

让我们总结一下 Java 中异步编程的规则:

  • 要等待,就不要阻塞系统线程:等待(I/O、超时或其他操作)要么在虚拟线程中进行,要么通过给 [CompletableFuture] 附加后续操作来进行;
  • 对于新代码,优先使用虚拟线程:编写阻塞的、顺序的、可读的代码(循环、[try / catch]、普通的局部变量),由 [Executors.newVirtualThreadPerTaskExecutor()] 执行;每个任务一个虚拟线程,绝不要使用虚拟线程池;
  • 使用 [CompletableFuture] 来组合操作,或者使用返回 [CompletableFuture] 的 API([HttpClient.sendAsync]、响应式库);此时我们选择后续操作的执行器([xxxAsync(..., executor)]),并且绝不在共享池中执行阻塞操作;
  • 不要在后续操作[join()] 或 [get()] 中或 GUI 线程里使用 :这些等待会阻塞执行它们的线程。它们应当放在主程序或虚拟线程中;
  • 虚拟线程用于等待,而不是计算:对于计算,请使用按处理器数量确定大小的平台线程池,或并行流;
  • 使用 [Semaphore] 来限制对稀缺资源的访问,而不是依靠线程池的大小;
  • 取消是协作式的:通过 [Future.cancel(true)] 取消任务,这会中断其线程;被中断的任务应优雅地终止;[InterruptedException] 绝不能被掩盖(要么传播它,要么重置中断标志)。并且请记住,[CompletableFuture.cancel] 不会中断任何东西;
  • 限制等待时间:[orTimeout]、[completeOnTimeout]、[get(timeout, unit)];如果放弃等待,就自行终止该操作;
  • 先启动,再等待:要同时运行多个相互独立的操作,先把它们全部启动,然后再等待它们([allOf]、[invokeAll]、执行器的 [close] 方法);
  • 已启动的操作必须被等待或监控:被遗忘的操作会隐藏它的异常(用 [exceptionally]、[whenComplete] 来处理它们);通过回溯 [CompletionException] 或 [ExecutionException],我们寻找根本原因。

下表总结了平台线程与阻塞等待的世界(上一章)、[CompletableFuture] 的世界以及虚拟线程的世界之间的对应关系:

平台线程,阻塞等待
CompletableFuture
虚拟线程
[Thread.sleep(1000)] (阻塞线程)
[new CompletableFuture<Void>().completeOnTimeout(null, 1, SECONDS)]
[Thread.sleep(1000)] (释放载体线程)
[thread.start()] 之后接 [thread.join()]
[supplyAsync(...)] 之后接 [join()] 或一个后续操作
[executor.submit(...)] 之后接 [get()]
等待多个线程(在循环中使用 [join] )
[allOf(...)]、[anyOf(...)]
[invokeAll(...)]、[ExecutorCompletionService]、[close()]
回调方法([CompletionHandler])
[thenApply]、[thenCompose]、[thenCombine]
阻塞调用之后的代码
围绕 [get()] 的 [try / catch] ([ExecutionException])
[exceptionally]、[handle]、[whenComplete]
[try / catch](标准)
[thread.interrupt()]
[cancel(...)] (不会中断任何东西)
[future.cancel(true)] (中断线程)
[future.get(timeout, unit)]
[orTimeout(...)]、[completeOnTimeout(...)]
[future.get(timeout, unit)]
固定大小的线程池
后续操作执行器 [xxxAsync]
[Semaphore]
[BlockingQueue] (阻塞线程)
[Flow]、[SubmissionPublisher]
[BlockingQueue] (释放载体线程)
[ScheduledExecutorService]
[completeOnTimeout]、[delayedExecutor]
在循环中使用 [Thread.sleep]

接下来的章节将应用这些规则:使用 JDBC(第 10 章)和 Hibernate(第 11 章)访问数据库,它们的 API 操作是阻塞的,天然适用于虚拟线程;通过虚拟线程为每个客户端提供服务的 TCP 服务器,以及 [HttpClient] 客户端(第 12 章);Spring Boot Web 服务,其中 Tomcat 服务器可以通过虚拟线程处理每个请求;以及它们的客户端(第 13 章)。