JDK8 CompletableFuture.supplyAsync how to deal with interruptedException

前端 未结 4 565
暖寄归人
暖寄归人 2020-12-17 15:30
CompletableFuture.supplyAsync(
() -> {
    transporter.write(req);
    //here take the value from a blocking queue,will throw a interruptedException
    return re         


        
4条回答
  •  忘掉有多难
    2020-12-17 16:12

    As lambda functions don't support throwing exceptions, I think Java developers will need a new paradigm. One thing that comes to mind is as follows:

    public class ResultWrapper {
        E exception;
        R result;
    }
    

    Lambda functions can return instances of this wrapper. (Edit: your case)

    CompletableFuture> aFuture = ...;
    ...
    aFuture.supplyAsync(
    () -> {
        try {
            transporter.write(req);
        } catch(InterruptedException e) {
            ResultWrapper r = new ResultWrapper<>();
            r.exception = e;
            r.result = null;
            return r;
        }
        ...
    },  executorService);
    

提交回复
热议问题