In Java 8, is it better for interface or abstract class to define APIs returning CompletableFuture instead of returning Future? Considering it is ugly converting Future to CompletableFuture and the fact that CompletableFuture will give the caller more flexibility of using functional style directly, what could be a good reason for an API to just return Future?
CompletableFuture is used for asynchronous programming in Java. Asynchronous programming is a means of writing non-blocking code by running a task on a separate thread than the main application thread and notifying the main thread about its progress, completion or failure.
As a result: Future transferes single value using synchronous interface. CompletableFuture transferes single value using both synchronous and asynchronous interfaces. Rx transferes multiple values using asynchronous interface with backpressure.
Class CompletableFuture<T> A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage , supporting dependent functions and actions that trigger upon its completion.
It just provides a get() method which blocks until the result is available to the main thread. Ultimately, it restricts users from applying any further action on the result. You can create an asynchronous workflow with CompletableFuture. It allows chaining multiple APIs, sending ones to result to another.
Thought I would come back to this and provide some updates on my final decisions:
For my own code/design, I went with using CompletableFuture as the return type, because
protected abstract method of an internal part that I want to make extensible;CompletableFuture is an added benefit/reminder/encouragement of using functional style to the future devs.With that being said, I would definitely use the CompletableStage interface as the return type, had I been designing a public API, because:
CompletableStage has a method CompletableFuture<T> toCompletableFuture().My 2 cts:
So you should probably assess the likelihood that you will want to return something other than a CompletableFuture in the future (haha) and decide accordingly.
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