Home > Net >  CompletableFuture, run asynchronous code after "join"
CompletableFuture, run asynchronous code after "join"

Time:05-12

I'm facing some trouble after some month only on Javascript/Typescript.

For example, let see this snippet:

@Test
    public void testAsync(){
        CompletableFuture.supplyAsync(()->{
            try{
                Thread.sleep(10000);
                System.out.println("After some seconds");
            }catch(InterruptedException exc){
                return "Fail";
            }
            return "Done";
        }).thenAccept(s->System.out.println(s)).join();

        System.out.println("should write before After some seconds statement");
    }

I was expecting the last system.out.println to run before the CompletableFuture but it await the complete of the Future.

So, what I got is: "After some seconds" "Done" "should write before After some seconds statement"

What I want: "should write before After some seconds statement" "After some seconds" "Done"

How can I achieve that?

CodePudding user response:

Store the future in a variable, print the statement, then join() to wait for the result:

CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
    try {
        Thread.sleep(10000);
        System.out.println("After some seconds");
    } catch (InterruptedException exc) {
        return "Fail";
    }
    return "Done";
}).thenAccept(s -> System.out.println(s));
System.out.println("should write before After some seconds statement");
future.join();

As for the explanation, the javadoc of the .join() method says:

Returns the result value when complete, or throws an (unchecked) exception if completed exceptionally

That means, if you call .join() chained to thenAccept(), it means that you will first wait for the supplyAsync() to end, then will thenAccept(), and will wait for such result via the join().

Hence, you will reach your System.out.println("should write before After some seconds statement"); just after all operations are completed.

If your objective was to wait for the future before completing the test, then you should call the join() after printing with the main thread, not before.

  • Related