JDK8 CompletableFuture.supplyAsync如何处理interruptedException [英] JDK8 CompletableFuture.supplyAsync how to deal with interruptedException
本文介绍了JDK8 CompletableFuture.supplyAsync如何处理interruptedException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
CompletableFuture.supplyAsync(
() -> {
transporter.write(req);
//here take the value from a blocking queue,will throw a interruptedException
return responseQueue.take();
}, executorService);
处理interruptedException的常用方法是再次中断或直接抛出interruptedException,但两者都无法工作。有人有想法吗?
The common method to deal with interruptedException is either to interrupt again or direct throw interruptedException, but both cannot work. Anyone have the idea?
推荐答案
我改变了这样的代码。
CompletableFuture<Rep> result = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
transporter.write(req);
try {
Rep rep = responseQueue.take();
result.complete(rep);
} catch (InterruptedException e) {
result.completeExceptionally(e);
Thread.currentThread().interrupt();
} catch (Exception e) {
result.completeExceptionally(e);
}
}, executorService);
return result;
这篇关于JDK8 CompletableFuture.supplyAsync如何处理interruptedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文