JDK8 CompletableFuture.supplyAsync how to deal with interruptedException

completablefuture supplyasync vs runasync
completablefuture supplyasync checked exception
completablefuture.allof example
completablefuture.runasync unit test
interruptedexception java 8
completablefuture run in parallel
java stream completablefuture
completablefuture geeksforgeeks
CompletableFuture.supplyAsync(
() -> {
    transporter.write(req);
    //here take the value from a blocking queue,will throw a interruptedException
    return responseQueue.take();
},  executorService);

The common method to deal with interruptedException is either to interrupt again or direct throw interruptedException, but both cannot work. Anyone have the idea?

I change the code like this.

    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;

CompletableFuture can't be interrupted, Java 8+ CompletableFuture example with error handling. CompletableFutureGreeting.java. CompletableFuture.supplyAsync(()-> {. try {. Thread.sleep(5000);. }  CompletableFuture.supplyAsync supplyAsync accepts a Supplier as an argument and complete its job asynchronously. The result of supplier is run by a task from ForkJoinPool.commonPool() as default. We can also pass our Executor. Finally supplyAsync method returns CompletableFuture on which we can apply other methods. CompletableFuture.thenApply

I ran into the same question, but after reading more from comments here and reference book I think you can do either one of these two:

1 (what I end up doing):

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

or 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();

I know the 2nd one does not use the executorService, but I feel the whole point of using CompletableFuture is utilizing the CompletionStage APIs in functional-style.

Java 8+ CompletableFuture example with error handling · GitHub, supplyAsync(() -> { System.out.println("running task"); return 1 / 0; }) . To handle exception (other than using try/catch), CompletableFuture API provides special chain How to find first and last element of Java 8 stream? @Miguel get differs from join by wrapping exceptions in an ExecutionException instead of CompletionException.This provides no improvement to the catch side. It also requires the caller to handle InterruptedException, which makes it more complicated.

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<R, E extends Exception> {
    E exception;
    R result;
}

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

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

Java CompletableFuture - Exception Handling, unsplash-logorawpixel Java 8 has introduced a lot of features. With Addition of Exception Handling - Future does not provide any construct for Exception Handling. All these catch (ExecutionException | InterruptedException e) { fail("​No CompletableFuture<String> supplyAsync = CompletableFuture. Java 8 came up with tons of new features and enhancements like Lambda expressions, Streams, CompletableFutures etc. In this post I’ll give you a detailed explanation of CompletableFuture and all its methods using simple examples.

@antak mentioned it buried in a comment, but I think the correct answer here is:

For CompletableFuture.supplyAsync() wrap it in java.util.concurrent.CompletionException and rethrow it.

So the sample code would look something like:

CompletableFuture.supplyAsync(
    () -> {
        transporter.write(req);
        try {
            //here take the value from a blocking queue,will throw a interruptedException
            return responseQueue.take();
        }
        catch (InterruptedException e) {
            throw new CompletionException(e);
        }
    },  executorService);

Write Clean Asynchronous Code With CompletableFuture Java-8 , Quick and practical guide to Java 8's CompletableFuture. combining, executing asynchronous computation steps and handling errors. during a computation) and InterruptedException (an exception signifying that a Static methods runAsync and supplyAsync allow us to create a CompletableFuture  InterruptedException is a permanent source of pain in Java, for junior developers especially. But it shouldn't be. It's a rather simple and easy-to-understand idea. Let me try to describe and

Guide To CompletableFuture, supplyAsync() is a static method of CompletableFuture introduced in Java 8. ExecutionException; public class SupplyAsyncExample1 { public static void main​(String[] args) throws InterruptedException, ExecutionException  Returns a new CompletableFuture that is completed when all of the given CompletableFutures complete. If any of the given CompletableFutures complete exceptionally, then the returned CompletableFuture also does so, with a CompletionException holding this exception as its cause.

Java CompletableFuture supplyAsync(), CompletableFuture also implements Future with the following policies: public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) future completed exceptionally: InterruptedException - if the current thread was interrupted of this functionality are available using methods whenComplete and handle . Preface For Node developers, non blocking asynchronous programming is something they are proud of. In JDK8, the concept of non blocking asynchronous programming is also introduced.

CompletableFuture (Java Platform SE 8 ), In this tutorial you'll learn What CompletableFuture is and how to use CompletableFuture for Java 8 came up with tons of new features and enhancements like Lambda Future API does not have any exception handling construct. Run a task asynchronously and return the result using supplyAsync() -. 2. Synchronous exception handling. And if I do not like partial results or asynchronous type exception handling the CompletableFuture.allOf() provides the handy mechanism to deal with that.

Comments
  • "but both cannot work." => why?
  • both have compiler error. if direct throw exception, compiler will show unhandled exception, if catch it and call Thead.current.interrupt, compiler will show must return a T type.
  • Yes you need to return or throw. If you decide to return null, for example: try { return queue.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; }
  • suppose future represent a compute result which is a normal value or a exception, i feel it should be a way set the exception to the future, it is better than set null.
  • I think lambda functions don't support throwing exceptions so throwing an exception is out of question. The sole thing you can do here is to return something.
  • What you have done is equivalent to mine. Alas, CompletableFuture<Rep> result can be replaced by ANY class that conforms to the "result or exception" paradigm. For example you can add get, complete and completeExceptionally methods to ResultWrapper and use ResultWrapper rep = new ResultWrapper();. It's quite a coincidence that you encountered this lambda function limitation using CompletableFuture and again you solved it using CompletableFuture, making use of those methods that you used.
  • Yes,but completablefuture already has the abstraction for a compute result,so I don't want to create new type for the same.
  • If you are working with other people, this may confuse the readers of your code. If not, great that it worked for you.
  • That is because future and promise two concepts into one type completablefuture in java. Return an completablefuture could make all the invoke asynchronous due to there are many methods in it.
  • CompletableFuture.runAsync use is not really necessary here, since you are not using return value; if you want to save some cycles, you can create ForJoinTask and execute it in ForkJoinPool#commonPool. Its slightly more code, but you'll avoid creating few instances and writing to volatile fields, so it should perform better.
  • Your second solutions can be improved. See stackoverflow.com/a/28961083/868941 for detailled explanation.