Manikandan Kbk DIP
Manikandan Kbk DIP

Reputation: 483

What is the difference between Future and Completable future in this regards?

Use case example

What is the difference between using future vs completable future in the following example regards.

One of the main use, I read is with .apply() in completable future you can wire multiple methods.

Isn't it the case with Future to wire the methods inside a method() and call that method() {which wired them} in a separate thread.

I find both of them doing the same thing. Can anyone please explain?

class FutureExample {

    static boolean method1() {
        return true;
    }
    static boolean method2(boolean m) {
        return m;
    }

    static boolean method() {
        boolean v = method1();
        return method2(v);
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(1); //initialize to 1 for stackoverflow question
        Future<Boolean> future = service.submit(FutureExample::method);
    }
}

VERSUS

class CompletableFutureExample {

    static boolean method1() {
        return true;
    }
    static boolean method2(boolean m) {
        return m;
    }

    public static void main(String[] args) {
        CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(CompletableFutureExample::method1).thenApply(CompletableFutureExample::method2);
    }
}

Upvotes: 2

Views: 3104

Answers (2)

radistao
radistao

Reputation: 15504

  1. In the first case (with Future only):

    • both methods are executed always in the same thread and this thread is blocked till both functions are done

    • no asynchronous exception handling

    • you can't easily combine/modify the execution chains: you always need to declare a new method for each function combinations

In this particular example the difference is not significant. The real power of CompletableFuture(or more generally -- CompletionStage) appears when you need to combine/merge the results of different asynchronous calls, handle exceptions of the entire chain, manage threads etc.

Upvotes: 1

Evgeny Shagov
Evgeny Shagov

Reputation: 21

  1. CompletableFuture is used for writing non-blocking code by running a task on a separate thread than the main thread and notifying the same about the progress. It could has two types of result:
    • Compleated
    • Failure

The main difference in this case is that you have possibility to complete a Future unit by using method .compleate(T t).

  1. With CompletableFuture you could attache Callable method:
    • thenAccept(Function f)
    • thenApply(...)
    • thenRun(...)

With Future you do not get notified when it is complete, with CompletableFuture you have this posibility.

I hope that I answered to your question. Have a nice day.

Upvotes: 1

Related Questions