优秀的编程知识分享平台

网站首页 > 技术文章 正文

CompletableFuture.failedFuture 在 java 8中的替代方法

nanyue 2025-07-14 20:19:34 技术文章 1 ℃

在 Java 8 中,CompletableFuture 没有提供原生的 failedFuture() 方法(该方法在 Java 9 引入)。以下是几种在 Java 8 中实现相同功能的替代方案:

方案 1:手动创建异常完成的 Future(最常用)



public static <T> CompletableFuture<T> failedFuture(Throwable ex) {

CompletableFuture<T> future = new CompletableFuture<>();

future.completeExceptionally(ex);

return future;

}


// 使用示例

CompletableFuture<String> future = failedFuture(new IOException("Connection failed"));

future.exceptionally(e -> {

System.err.println("Error: " + e.getMessage());

return null;

});



方案 2:使用 supplyAsync 包装异常




CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {

throw new RuntimeException("Forced failure");

});


// 异常处理

future.handle((result, ex) -> {

if (ex != null) {

System.out.println("Caught: " + ex.getCause().getMessage());

}

return result;

});



方案 3:组合操作(更复杂的场景)




// 先创建正常 Future 再组合异常

CompletableFuture<String> success = CompletableFuture.completedFuture("OK");

CompletableFuture<String> failure = success.thenApply(s -> {

throw new IllegalStateException("Transformed to failure");

});


// 统一处理

failure.exceptionally(ex -> {

System.out.println("Transformed error: " + ex.getMessage());

return "fallback";

});



方案 4:使用第三方库(如 Guava)




// 添加 Guava 依赖

import com.google.common.util.concurrent.SettableFuture;


SettableFuture<String> future = SettableFuture.create();

future.setException(new RuntimeException("Guava failure"));


// 转成 CompletableFuture

CompletableFuture<String> completable = CompletableFuture.supplyAsync(() -> {

try {

return future.get();

} catch (Exception e) {

throw new CompletionException(e);

}

});


对比总结


方法

优点

缺点

手动创建异常 Future

简单直接,无依赖

需自定义工具方法

supplyAsync 包装异常

无需额外方法

异常堆栈可能包含冗余信息

组合操作

适合已有 Future 的转换

代码稍复杂

Guava 库

功能强大

引入第三方依赖

Java 9+ 原生方法(参考)



// Java 9+ 原生方法

CompletableFuture<String> failure = CompletableFuture.failedFuture(

new IOException("File not found")

);



迁移建议:

  • 若项目停留在 Java 8,推荐使用 方案 1(自定义工具方法)
  • 若可升级到 Java 9+,直接使用原生 failedFuture()
  • 若已使用 Guava,可考虑 方案 4 保持风格统一

Tags:

最近发表
标签列表