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.
A ListenableFuture represents the result of an asynchronous computation: a computation that may or may not have finished producing a result yet. It's a type of Future that allows you to register callbacks to be executed once the computation is complete, or if the computation is already complete, immediately.
Future vs CompletableFuture. CompletableFuture is an extension to Java's Future API which was introduced in Java 5. A Future is used as a reference to the result of an asynchronous computation.
CompletableFuture is inherently thread-safe The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation.
A CompletableFuture is an extension to Java's Future API which was introduced in Java 8. A Future is used for asynchronous Programming. It provides two methods, isDone() and get(). The methods retrieve the result of the computation when it completes.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With