SL Official
SL Official

Reputation: 21

CompletableFuture completion sequence in JAVA

I wrote a simple program

import java.util.concurrent.*;
public class TestCompletableFuture {
    
    public static void main(String[] args) throws Exception {
        CompletableFuture<Void> future = new CompletableFuture<Void>()
            .whenComplete((res, exc) -> {
                System.out.println("inside handle.");
                if (exc != null) {
                    System.out.println("exception.");
                }
                System.out.println("completed.");
            }
        );

        future.completeExceptionally(new Exception("exception"));
        System.out.println("finished.");
    }
}

the output of the code:

finished.

When the main thread calls future, my understanding is. The method supplied into CompletableFuture should be called by completeExceptionally(). whenComplete().

Why isn't that the case?

Upvotes: 2

Views: 32

Answers (1)

Lakshan Fernando
Lakshan Fernando

Reputation: 21

This is a result of you finishing the incorrect future. To see the whenComplete in action, you must obtain a reference to the first step and finish it:

public class TestCompletableFuture {

    public static void main(String[] args) throws Exception {

        /** get reference */
        CompletableFuture<Void> future = new CompletableFuture<>();
        
        /** configure the action that to be run when the future is complete */
        CompletableFuture<Void> future2 = future
                .whenComplete((res, exc) -> {
                            System.out.println("inside handle.");
                            if (exc != null) {
                                System.out.println("exception.");
                            }
                            System.out.println("completed.");
                        }
                );

        future.completeExceptionally(new Exception("exception"));
        System.out.println("finished.");
    }
}

The code is now self-explanatory... Run the (res, exc) -> action when the future is finished. And simply use completeExceptionally(...) on the future to bring about that completion.

Also to be noted is the exceptional completion of all the aforementioned stages (futures) at this time:

System.out.println(future.isDone()); // true
System.out.println(future2.isDone()); // true

System.out.println(future.isCompletedExceptionally()); // true
System.out.println(future2.isCompletedExceptionally()); // true

Upvotes: 2

Related Questions