在 completionstage 的链式调用中,ortimeout 方法本身不接受任何函数参数,它仅用于设置超时时间。若要在超时时执行特定逻辑(如返回默认值或抛出异常),应使用 exceptionally 或 handle 方法捕获 timeoutexception。这两个方法接收 function 或 bifunction 作为参数,从而实现基于条件的处理。

orTimeout 与 exceptionally 如何配合使用?
通过先调用 orTimeout 触发超时异常,再在后续节点使用 exceptionally 拦截该异常并返回替代结果,即可实现超时降级。例如,当任务超过指定秒数未完成时,程序会进入 exceptionally 分支,返回一个预设的默认值,而不是让异常向上传播导致程序中断。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
public class TimeoutExample {
public static void main(String[] args) throws Exception {
CompletionStage<string> stage = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000); // 模拟耗时操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Success";
})
.orTimeout(1, TimeUnit.SECONDS) // 设置1秒超时
.exceptionally(ex -> {
if (ex instanceof java.util.concurrent.TimeoutException) {
return "Timed Out"; // 超时返回默认值
}
return "Error: " + ex.getMessage();
});
System.out.println(stage.toCompletableFuture().get());
}
}</string>
运行上述代码,由于睡眠时间为3秒而超时设置为1秒,控制台将输出 Timed Out。这验证了 orTimeout 成功触发了超时机制,且 exceptionally 正确捕获了 TimeoutException 并返回了字符串结果。
handle 方法如何处理正常结果与超时异常?
如果需要在超时时保留原始状态或区分成功与失败,可以使用 handle 方法。该方法同时接收计算结果和异常对象,当发生超时时,结果参数为 null,异常参数为 TimeoutException。这种方式比 exceptionally 更灵活,因为它允许在成功时直接透传结果,而在失败时进行统一处理。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
public class HandleExample {
public static void main(String[] args) throws Exception {
CompletionStage<string> stage = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(500); // 快速完成
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Fast Result";
})
.orTimeout(1, TimeUnit.SECONDS)
.handle((result, ex) -> {
if (ex != null) {
return "Failed: " + ex.getClass().getSimpleName();
}
return "Result: " + result;
});
System.out.println(stage.toCompletableFuture().get());
}
}</string>
在此示例中,任务在500毫秒内完成,未触发超时。因此 handle 中的 ex 为 null,result 为 Fast Result,最终输出 Result: Fast Result。若将睡眠时间改为2秒,则输出将变为 Failed: TimeoutException。这表明 handle 能够根据执行状态动态调整返回值。
超时异常的具体类型是什么?
在使用 orTimeout 时,抛出的异常类型为 java.util.concurrent.TimeoutException。这是 java.util.concurrent 包下的标准异常,继承自 ExecutionException。在 exceptionally 或 handle 中捕获该异常时,必须显式检查其类型,因为其他运行时异常也可能被传入。确认异常类型有助于避免误处理非超时导致的错误。
,
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











