
本文旨在解决java异步编程中,当`completablefuture`被不当嵌套时,调用`get()`或获取响应体时返回其状态而非实际结果的问题。通过分析错误根源,本文将展示如何正确地链式调用`completablefuture`,确保`thenapply`等方法能处理到期望的最终数据类型,从而避免获取到内部`completablefuture`对象本身。
在Java的异步编程中,CompletableFuture是一个强大的工具,用于处理非阻塞操作。然而,不恰当的使用方式可能导致难以预料的结果。一个常见的陷阱是当一个CompletableFuture的内部值本身又是另一个CompletableFuture时,对其外部CompletableFuture执行操作可能会得到内部CompletableFuture对象本身的状态信息,而非其最终解析的数据。
考虑以下场景,一个Spring Boot应用提供了一个异步API:
不正确的RestController实现:
@RestController
public class WorkerJController {
@Autowired
private WorkerJService service;
@GetMapping(value = "/JobList", produces = MediaType.APPLICATION_JSON_VALUE)
public CompletableFuture<ResponseEntity> getJobListFunction() throws JsonProcessingException, InterruptedException {
// 问题所在:service.getJobListFunction() 已经返回一个 CompletableFuture<String>
// CompletableFuture.completedFuture() 又将其包装了一层
return CompletableFuture.completedFuture(service.getJobListFunction()).thenApply(ResponseEntity::ok);
}
}Service层实现:
立即学习“Java免费学习笔记(深入)”;
@Service
public class WorkerJService {
public static ArrayList<someThing> randomList = new ArrayList<>();
@Async
public CompletableFuture<String> getJobListFunction() throws JsonProcessingException, InterruptedException {
randomList.add(new someThing("abc", "dfe"));
ObjectMapper mapper = new ObjectMapper();
TimeUnit.SECONDS.sleep(5); // 模拟耗时操作
return CompletableFuture.completedFuture(mapper.writeValueAsString(randomList));
}
}当客户端通过HttpClient发送异步请求并尝试获取响应体时:
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(20))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8080/JobList"))
.timeout(Duration.ofMinutes(2))
.GET()
.build();
CompletableFuture<HttpResponse<String>> cf = client
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
// 假设这里在客户端获取了响应,并尝试访问其内容
// cf.get().body() 可能会得到类似 {"cancelled":false,"done":true,"completedExceptionally":false,"numberOfDependents":0} 的状态信息客户端接收到的响应体不是预期的JSON字符串,而是{"cancelled":false,"done":true,"completedExceptionally":false,"numberOfDependents":0}这样的CompletableFuture状态信息。
问题的核心在于WorkerJController中的这行代码:
return CompletableFuture.completedFuture(service.getJobListFunction()).thenApply(ResponseEntity::ok);
简而言之,我们创建了一个“双层”的CompletableFuture,而thenApply只处理了外层,将内层CompletableFuture本身作为数据传递了出去。
解决这个问题的方法是避免不必要的嵌套,直接对 service.getJobListFunction() 返回的 CompletableFuture 进行链式操作。
修正后的RestController实现:
@RestController
public class WorkerJController {
@Autowired
private WorkerJService service;
@GetMapping(value = "/JobList", produces = MediaType.APPLICATION_JSON_VALUE)
public CompletableFuture<ResponseEntity<String>> getJobListFunction() throws JsonProcessingException, InterruptedException {
// 直接对 service.getJobListFunction() 返回的 CompletableFuture 进行链式操作
return service.getJobListFunction().thenApply(ResponseEntity::ok);
}
}解释:
通过这种方式,thenApply 能够正确地处理到 CompletableFuture 最终解析的 String 值,并将其封装到 ResponseEntity 中,而不是封装 CompletableFuture 对象本身。
正确使用 CompletableFuture 的链式操作是编写高效、可维护的异步Java代码的关键。通过避免不必要的 CompletableFuture 嵌套,并根据转换操作的返回值类型(是否为 CompletableFuture)选择合适的链式方法(thenApply 或 thenCompose),可以确保我们始终能够获取到异步操作的最终实际结果,而不是中间状态或未解析的对象。理解这些细微之处将大大提升异步编程的质量和可靠性。
以上就是Java中正确处理嵌套CompletableFuture并获取实际结果的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号