I thought I understood the goal of CompletableFuture, introduced by Java8. Then I read this: https://medium.com/swlh/completablefuture-a-simplified-guide-to-async-programming-41cecb162308
In this article, the developer starts (or completes) a CompletableFuture INSIDE a new thread, which doesn't compute with me.
Can someone please explain, why anyone would benefit from having a separate Thread() complete a CompletableFuture?
CompletableFuture<Double> futureResult = new CompletableFuture<>();
new Thread( ()-> {
try{
//some long process
futureResult.complete(10.0);
}catch(Exception e){
futureResult.completeExceptionally(e);
}
}).start();
return futureResult;
Edit: As pointed out in the comments, and accepted answer, unsurprisingly, my confusion was rooted in my misunderstanding of CompletableFuture. In hindsight, it seems pretty obvious that, the new asynchronous activity would need to be started somewhere so why not in a new thread, since that new activity would be blocking?
Excellent, for gaining insight into CompletableFuture.
A CompletableFuture implies that it is executing, so when you provide one you should have it started some how. Your example uses a Thread which doesn't give you much control.
If you don't care you should use CompletableFuture.completeAsync which would take care of the executor/thread.
In the provided code, the Thread is doing all of the work, and then 'completing' the future.