Reputation: 483
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
Reputation: 15504
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
Reputation: 21
The main difference in this case is that you have possibility to complete a Future unit by using method .compleate(T t).
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