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

标签 java multithreading parallel-processing future completable-future

我正在尝试做类似的事情

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/

相关文章:

java - 并行化 for 循环

java - Primefaces 验证码消失或不更新/刷新无效输入?

java - 将javascript对象数组作为参数发送到 Controller

python - 如何在python中的多个线程之间正确共享信息?

php - 并行执行函数

ruby - 附加到 Ruby 中的数组

memory - Go(lang) 中的地址空间是什么?

运行时不显示 Java 字符串

java - UtteranceProgressListener 不适用于 Android TTS

php - curl_multi_exec使用多少个线程?