Java 检测完整未来链中的超时
是否有任何可能的安全方法来检测一个完整的未来链中的超时Java 检测完整未来链中的超时,java,multithreading,completable-future,Java,Multithreading,Completable Future,是否有任何可能的安全方法来检测一个完整的未来链中的超时 O someValue = CompletableFuture.supplyAsync(() -> { ... // API Call ... }).thenApply(o -> { ... }).thenApply(o -> {
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调用结果的机会。在这样的链中进行缓存的唯一机会是如下所示,这对计时API调用本身没有帮助
.thenApplyAsync(o -> {
cache = o;
// do something
}).thenApplyAsync(o -> {
cache = o;
// do something more
}).get(10, TimeUnit.SECONDS);
然而,通读给了我一个想法,如果你做了如下的事情呢
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);
SynchronousQueue q=newsynchronousqueue();
CompletableFuture.SupplySync(()->{
//API调用
}。然后接受(结果->{
cache.put(result);//缓存值
q、 提供(结果);//如果主线程仍然存在,则向主线程提供值
}
);
//主线程等待10秒,等待将值异步提供到队列中
//如果超时,则返回null,但任何操作都已完成
//在仍然执行q.offer(结果)之前
返回队列。轮询(10,时间单位。秒);
10秒钟内未完成的API调用仍会被处理到缓存中,因为它是异步接受的,超时发生在主线程中,而不是
CompletableFuture
链中,即使原始请求不会得到结果(我想必须优雅地处理它).1+,我正朝着同一个方向努力寻找答案。明显复杂的部分是正确地书写交换器。@Eugene我实际上想到的是股票(尽管很少使用)哦!我试图用一个SynchronousQueue
来实现这一点,我看到Exchanger
在同一个逻辑主体上工作。需要看一下.thx的链接。事实上Exchanger
在这里不起作用,因为如果主线程退出了该方法,那么接受线程就会挂起,所以SynchronousQueue
I这就是我要做的。我真的需要停止尝试使用交换器,它是无用的。是的,它几乎和我想写的一样。很漂亮,伊姆霍。