有没有可能安全的方法来检测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/