java - 检测CompletableFuture链中的超时

标签 java multithreading completable-future

有没有可能安全的方法来检测CompletableFuture链中的超时?

O someValue = CompletableFuture.supplyAsync(() -> {
                ...
                // API Call
                ...
            }).thenApply(o -> {
                ...
            }).thenApply(o -> {
                // If the chain has timed out, I still have 'o' ready here
                // So at least cache it here, so it's available for the next request
                // Even though the current request will return with a 'null'
                ...
            }).get(10, TimeUnit.SECONDS);
// cache 'someValue'
return someValue;
它成功完成,没有超时,我可以使用'someValue'并执行任何操作
如果超时,则抛出TimeoutException,即使该值仍在后台处理,我也会丢失该值
这个想法是,即使超时,并且由于线程中的API调用仍在后台完成并返回响应,所以我可以使用该值(例如,进行缓存)

最佳答案

至少不以您显示的方式。抛出异常后,即使API调用完成了,您也没有机会接触到它。在这样的链中进行缓存的唯一机会如下所示,这对超时的API调用本身无济于事

.thenApplyAsync(o -> {
    cache = o;
    // do something
}).thenApplyAsync(o -> {
    cache = o;
    // do something more
}).get(10, TimeUnit.SECONDS);
但是,通过阅读this给了我一个主意,那就是如果您执行了以下操作,该怎么办
SynchronousQueue<Result> q = new SynchronousQueue<>();
CompletableFuture.supplyAsync(() -> {
    // API call
}.thenAccept(result -> {
    cache.put(result);   // cache the value
    q.offer(result); // offer value to main thread, if still there
}
);

// Main thread waits 10 seconds for a value to be asynchronously offered into the queue
// In case of timeout, null is returned, but any operations done
// before q.offer(result) are still performed

return queue.poll(10, TimeUnit.SECONDS);
在10秒内未完成的API调用仍会被处理到缓存中,因为它被异步接受,并且超时发生在主线程中,而不是CompletableFuture链中,即使原始请求无法获得结果(我猜也是这样)必须优雅地处理它)。

关于java - 检测CompletableFuture链中的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66281271/

相关文章:

java - 如何自动运行测试?

java - 为什么我在 jdoconfig.xml 中收到错误?

multithreading - 线程启动而不调用它的启动方法

java - 返回在响应的特定条件下首先执行的 future

java - 如何使用 Netty 关闭异步 Http 请求的 AsyncHttpClient?

java - 如何使用 Java 对 MongoDB 中的文档进行批量更新?

java - 为什么我的应用程序内存不足?

multithreading - 如何在不调用 .Sync 的情况下处理 AsyncCalls 函数中抛出的异常?

c++ - tbb::parallel_reduce 对比 tbb::combinable 对比 tbb::enumerable_thread_specific

Spring将请求范围的bean提升到子线程(HttpServletRequest)