JDK8 CompletableFuture.supplyAsync 如何处理中断的异常

2022-09-02 21:00:30
CompletableFuture.supplyAsync(
() -> {
    transporter.write(req);
    //here take the value from a blocking queue,will throw a interruptedException
    return responseQueue.take();
},  executorService);

处理中断异常的常用方法是再次中断或直接抛出中断异常,但两者都不起作用。有人有这个想法吗?


答案 1

我像这样更改代码。

    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;

答案 2

我遇到了同样的问题,但是在阅读了更多来自此处的评论和参考书之后,我认为您可以执行以下两种方法之一:

1(我最终要做的):

CompletableFuture.runAsync(() -> {
    transporter.write(req);
    try {
        Rep rep = responseQueue.take();
        result.complete(rep);
    } catch (Exception e) {
        throw new CompletionException(e);
    }
}, executorService);
return result;

或 2:

CompletableFuture<Rep> result = new CompletableFuture<>();
new Thread(()-> {
    transporter.write(req);
    try {
        Rep rep = responseQueue.take();
        result.complete(rep);
    } catch (Exception e) {
        result.completeExceptionally(e);
    }
}).start();

我知道第二个没有使用,但我觉得使用ComppletableFuture的全部意义在于以函数式的方式使用CompendationStage API。executorService


推荐