gpt4 book ai didi

java - 如何并行调用独立函数并在使用 CompletableFuture 失败时抛出异常

转载 作者:行者123 更新时间:2023-12-03 12:47:06 25 4
gpt4 key购买 nike

我正在尝试做类似的事情

Optional<Order> orderDetails = orderRepository.findById(orderId);
if (orderDetails.isEmpty())
throw new OrderNotFoundException("Order not found!");

Optional<User> UserDetails = userRepository.findById(userId);
if (UserDetails.isEmpty())
throw new UserNotFoundException("User not found!");

List<OrderItem> ItemDetailsList = orderItemRepository.findByOrderIdOrderByItemIdAsc(orderId);

我想以非阻塞方式一起调用这三个服务方法,但如果其中任何一个调用失败并且不再继续,我想抛出错误。如果以上都可行,则执行后面的逻辑。

我正在考虑使用 allOff() 然后在使用 get 上 Futures 并在 Optional 为空时执行上述抛出错误的逻辑?

有更好的方法吗? 如果其中一个失败而其他任务仍在运行,则抛出错误并中止其他正在运行的任务。

最佳答案

CompletableFuture 是这里工作的错误工具。主要问题是你想要:

"...throw error and abort the other running tasks"

如果您阅读了CompletableFuture::cancel 文档所说的内容,您将看到:

mayInterruptIfRunning – this value has no effect in this implementation because interrupts are not used to control processing.

因此,即使您调用cancel,这也不会中断您的任务,它们仍会继续完成。因此,无法满足您的基本要求。

有一种方法可以为您要取消并关闭池的 CompletableFuture 创建自定义线程池,as an example here .但这并非易事,您的线程需要正确响应中断。

关于java - 如何并行调用独立函数并在使用 CompletableFuture 失败时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66622991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com