Listenablefuture vs Completablefuture

JavaCompletable Future

Java Problem Overview


I tried hard but didn't find any article or blog which clearly compares ListenableFuture and CompletableFuture, and provides a good analysis.

So if anyone can explain or point me to such a blog or article, it will be really good for me.

Java Solutions


Solution 1 - Java

Both ListenableFuture and CompletableFuture have an advantage over its parent class Future by allowing the caller to "register" in one way or another a callback to be called when the async action has been completed.

With Future you can do this:

ExecutorService executor = ...;
Future f = executor.submit(...);
f.get();

f.get() gets blocked until the async action is completed.

With ListenableFuture you can register a callback like this:

ListenableFuture listenable = service.submit(...);
    Futures.addCallback(listenable, new FutureCallback<Object>() {
                @Override
                public void onSuccess(Object o) {
                    //handle on success
                }
    
                @Override
                public void onFailure(Throwable throwable) {
                   //handle on failure
                }
            })

With CompletableFuture you can also register a callback for when the task is complete, but it is different from ListenableFuture in that it can be completed from any thread that wants it to complete.

CompletableFuture completableFuture = new CompletableFuture();
    completableFuture.whenComplete(new BiConsumer() {
        @Override
        public void accept(Object o, Object o2) {
            //handle complete
        }
    }); // complete the task
    completableFuture.complete(new Object())

When a thread calls complete on the task, the value received from a call to get() is set with the parameter value if the task is not already completed.

[Read about CompletableFuture][1] [1]: http://www.nurkiewicz.com/2013/05/java-8-definitive-guide-to.html

Solution 2 - Java

Guava AbstractFuture has its limitations:

  1. Listener is lists, but usually only 1 used - overkill. If multiple listeners are needed, handle it inside the next stage, or think about messaging.

  2. setException set return value as Exception, so user has to use instanceof to differentiate Exception or not at get() like guava AbstractFuture did.

  3. In Future pipeline, too many layers addListener() make code hard to read.

I prefer CompletableFuture.supply().thenApply().thenAccept().handle()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshutosh JhaView Question on Stackoverflow
Solution 1 - JavaLivia MoroianuView Answer on Stackoverflow
Solution 2 - JavasimpleView Answer on Stackoverflow