>_ SEEDOFWHALE / INDEX

技术笔记目录

按主题找文章。点标题看正文,技术索引可直达原文或视频。

[译] Java 虚拟线程把 Future 接入 CompletableFuture

授权转载与 AI 辅助翻译(非官方)
原作者及版权:© Gunnar Morling;首发:2025-07-17
英文原文:Converting Future to CompletableFuture With Java Virtual Threads
授权:英文原文及本简体中文译文均按 CC BY-SA 4.0 分享。编辑改动:增加中文翻译、译注和分类导航;保留完整英文正文,调整排版,外嵌演示以链接呈现。未暗示原作者认可本译文。

分类:Java 后端与交易 · Java 21、虚拟线程、异步组合
博客首页目录 · 一手技术资料总索引

中文译文

Java 21 及以上版本的虚拟线程,为把旧式 Future 转换成 CompletableFuture 提供了简洁的做法。

从 Java 8 开始,CompletableFuture API 可以用函数式、可组合的方式写异步操作。比如耗时较长、涉及外部 I/O 的方法,可以异步调用,结果一到就继续处理,而不用在调用方线程上等待:

CompletableFuture.supplyAsync(() -> getCustomerFromDb("Bob"))
    .thenApply(c -> getOrdersForCustomer(c.id()))
    .thenAccept(o -> System.out.println("Bob's orders: " + o));

遗憾的是,许多 Java 平台 API(例如 ExecutorService)和第三方库仍然暴露 Java 5 时代的 Future,而不是 CompletableFuture。两者都表示异步计算的结果,但后者不仅可以组合,也是推送式的:计算结果可用时,它会通知你。

反过来,Future 只支持拉取。要拿结果必须调用 get(),在结果出来前会阻塞当前线程,多少抵消了采用异步模型的意义。缓解办法是调用不阻塞的 isDone() 检查状态,结果没出来就先做别的事。

这种做法既不简洁,也不高效。因此我们会问:能不能把 Future 转成 CompletableFuture?第一种尝试如下:

public <T> CompletableFuture<T> toCompletableFuture(Future<T> future) {
  return CompletableFuture.supplyAsync(() -> {
    try {
      return future.get();
    } catch (InterruptedException | ExecutionException e) {
      throw new CompletionException(e);
    }
  });
}

这样可以把某个旧库返回的 Future 接到以 CompletableFuture 为基础的处理链里。但仔细看就会发现,问题只是换了地方:Future::get() 还是会阻塞执行 supplyAsync() 中 Lambda 的线程。没指定执行器时,用的是公共 ForkJoinPool。这个池由整个应用共享,不宜在其中阻塞线程。

另一种思路是用刚提到的 isDone():用另一个线程或定时器定期检查。确认结束后,再用 get() 取值、完成 CompletableFuture。这不会阻塞线程,但轮询太频繁会增加 CPU 开销,轮询太疏又会增加延迟。

退一步重新看第一种办法:阻塞线程真的总是坏事吗?自 Java 21 起有了虚拟线程,未必如此。虚拟线程开销很低,可以有几十万甚至几百万个。虚拟线程阻塞时,会从承载它的操作系统线程(载体线程)卸载,腾出载体去运行其他虚拟线程。等它解除阻塞才会重新挂到载体上。

在某些情形下,虚拟线程确实会占住载体线程,这叫固定(pinning)。典型例子是 Java 21 在 synchronized 块内执行阻塞操作;从 Java 24 起,该情形不再导致固定。本文讨论的用例不受固定影响。

怎么用虚拟线程做转换?给前面调用的 CompletableFuture::supplyAsync() 传一个由虚拟线程提供支持的执行器,或者直接启动一条虚拟线程,拿到原 Future 的结果后手动完成 CompletableFuture:

public <T> CompletableFuture<T> toCompletableFuture(Future<T> future) {
  CompletableFuture<T> completable = new CompletableFuture<T>();

  Thread.ofVirtual().start(() -> {
    try {
      completable.complete(future.get());
    } catch (InterruptedException | ExecutionException e) {
      completable.completeExceptionally(e);
    }
  });

  return completable;
}

虚拟线程解决了这个长期存在的集成问题。因为其开销轻量,旧的 Future API 可以平滑接入 CompletableFuture 的组合模式,不必在普通线程阻塞和轮询开销之间取舍。

译注:原示例为结果转换,并未实现双向取消传播;调用方若要求取消语义,需要另外设计和测试。


English Original

Converting Future to CompletableFuture With Java Virtual Threads

This post explores how virtual threads in Java 21+ provide an elegant solution for converting legacy Future objects into CompletableFuture instances.

Since Java 8, the CompletableFuture API provides a convenient way for performing asynchronous operations in a functional, composable way. This makes it very simple to call some long-running methods—​for instance involving external I/O—​asynchronously and process each result as soon as it is available, without blocking on any threads:

CompletableFuture.supplyAsync(() -> getCustomerFromDb("Bob"))
    .thenApply(c -> getOrdersForCustomer(c.id()))
    .thenAccept(o -> System.out.println("Bob's orders: " + o));

Unfortunately, many Java platform APIs, for instance ExecutorService, as well as 3rd party libraries, still don’t expose CompletableFuture, but the legacy Future type from Java 5.0 times. While both types represent the result of an asynchronous computation, CompletableFuture provides several advantages. Not only is it composable, it also is push-based, i.e. it notifies you when the computation result is available.

Future, on the other hand, only supports pull-style access: To retrieve the result value, you need to call the get() method, which will block the current thread until the result is available, thus somewhat defeating the purpose of using an asynchronous processing model to begin with. To mitigate the situation, you can check whether the Future has been completed by calling the (non-blocking) isDone() method, and do something else until the result finally is there.

This approach is neither very elegant nor efficient, which raises the question whether a Future can be converted into a CompletableFuture. A first attempt could look like so:

public <T> CompletableFuture<T> toCompletableFuture(Future<T> future) {
  return CompletableFuture.supplyAsync(() -> {
    try {
      return future.get();
    } catch (InterruptedException | ExecutionException e) {
      throw new CompletionException(e);
    }
  });
}

This lets you integrate a Future, for instance returned by some legacy library, into a CompletableFuture-based processing pipeline. However, closer inspection reveals that this only shifts the problem from one place to another: the call to Future::get() blocks the thread running the Lambda expression passed to supplyAsync(). By default, when not specifying a particular executor, this will be a thread of the common fork-join pool. Since this pool is shared globally across the application, blocking threads in it is undesirable.

Alternatively, you could envision a solution based on the aforementioned isDone() method: you could use another thread or a timer which regularly checks the future for completion, and once that’s the case, the CompletableFuture gets completed with the value obtained from get(). While this avoids any thread blocking, it either adds CPU overhead—​when calling isDone() with a very high frequency—​or it adds latencym when checking less frequently.

Now, taking a step back, let’s rethink the first solution. Is blocking a thread actually always bad? In fact, it is not, thanks to virtual threads, as available since Java 21. Virtual threads are cheap, you can have hundreds of thousands, or even millions of them. When a virtual thread blocks, it will be unmounted from the underlying operating system thread which is running it ("carrier thread"), thus freeing it for running other virtual threads. Only once the virtual thread gets unblocked, it will be mounted to a carrier again.

In certain situations, a virtual thread actually can block its carrier, a situation known as "pinning". Most notably, on Java 21 this would happen when calling a blocking operation from within a synchronized block. Starting with Java 24, this will not cause pinning any longer. The use case discussed in this post is unaffected by pinning.

How could we use virtual threads then to convert a Future into a CompletableFuture? One option would be to pass an executor backed by virtual threads when calling CompletableFuture::supplyAsync() in the solution above. Or, we could just start a virtual thread ourselves and manually complete a CompletableFuture object with the result of the original Future:

public <T> CompletableFuture<T> toCompletableFuture(Future<T> future) {
  CompletableFuture<T> completable = new CompletableFuture<T>();

  Thread.ofVirtual().start(() -> {
    try {
      completable.complete(future.get());
    } catch (InterruptedException | ExecutionException e) {
      completable.completeExceptionally(e);
    }
  });

  return completable;
}

Virtual threads provide an elegant solution to a long-standing integration challenge. Thanks to their lightweight nature, you can seamlessly bridge the gap between legacy Future-based APIs and modern CompletableFuture composition patterns, without the traditional trade-offs of thread blocking or polling overhead.

posted @ 2026-12-04 13:14  西门咬狗  阅读(5)  评论(0)    收藏  举报