With the introduction of CompletableFuture
in Java 8, the world of asynchronouse programming took a massive step forward. But one may wonder the real reason behind its introduction when we already had **Future **interfacesince Java 5. The real motivation behind CompletableFuture was to overcome certain limitations of **Future **interface:
1\. There was no way to make get() call non-blocking in Future.
2\. No support for exception handling.
3\. Chaining of callbacks was not supported.
4\. There was no way to explicitly complete the task.
In this article, we will see some common usage of CompletableFuture
.
First of all to create a new completableFuture
task, simply call the constructor
CompletableFuture<String> task = new CompletableFuture<String>();
Also, you can explicitly create a completed task
CompletableFuture<String> completedTask =
CompletableFuture.completedFuture("Some Value");
Or mark the task as completed by calling the complete
method. All the clients waiting for task to complete will get the specified result.
task.complete("Task completed forcefully");
To get the result of this CompletableFuture
we can call get()
method.
if(completedTask.isDone()){
completedTask.get();
}
#java #completablefuture #parallel-computing #tutorial #asynchronous-programming