completablefuture 的 ortimeout 方法用于为异步任务设置超时限制,当任务在指定时间内未完成时,会自动抛出 timeoutexception。调用该方法会返回一个新的 completablefuture,原任务继续运行但新实例的状态由超时控制。若需处理超时异常,应配合 exceptionally 或 handle 使用,避免程序因未捕获异常而中断。

orTimeout 如何与 thenApply 组合实现带超时的转换
将 orTimeout 放在 thenApply 之前,可以确保整个转换过程受超时保护。如果转换耗时超过设定值,后续步骤不会执行,而是直接触发异常处理逻辑。这种方式适用于需要限制总耗时的场景,例如网络请求加数据处理。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class TimeoutExample {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(2000); } catch (InterruptedException e) {}
return "Result";
})
.orTimeout(1, TimeUnit.SECONDS)
.thenApply(s -> s.toUpperCase())
.exceptionally(ex -> "Timed out: " + ex.getCause().getMessage());
System.out.println(future.get());
}
}
预期输出:Timed out: Timed out after 1 SECONDS
立即学习“Java免费学习笔记(深入)”;
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
orTimeout 对已完成任务的即时影响是什么
如果 CompletableFuture 在调用 orTimeout 前已经完成,该方法不会启动计时器,而是直接返回当前已完成的结果。这意味着超时机制仅对尚未完成的任务生效,已完成的实例不受影响,也不会抛出异常。这种设计保证了同步或快速返回的场景下行为的一致性。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class CompletedFutureTest {
public static void main(String[] args) throws Exception {
CompletableFuture<String> completed = CompletableFuture.completedFuture("Done");
CompletableFuture<String> withTimeout = completed.orTimeout(5, TimeUnit.SECONDS);
System.out.println(withTimeout.isDone()); // true
System.out.println(withTimeout.get()); // Done
}
}
预期输出:trueDone
当 orTimeout 触发后,原任务是否被取消
orTimeout 触发时,它会将自身的 CompletableFuture 标记为异常完成状态,但不会主动取消原始任务。原始任务仍在后台运行,直到其自然结束或被其他机制中断。这可能导致资源浪费,因此在长时间运行的任务中,建议结合 cancel(true) 或可中断的阻塞操作来释放资源。

















