What Is CompletableFuture Class
Posted By : Harish Modi | 30-May-2018
CompletableFuture is
and CompletableFuture class implements the Future Interface.when use of CompletableFuture your main thread does not wait/block
for the completion of the task and it
- Creating a CompletableFuture-
CompletableFuture<String> completableFuture = new CompletableFuture<String>();
- Using some method:
1:runAsync():If you want to run some background task asynchronously and don’t want to return anything from the task.
Example:
// Using Lambda Expression
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// Simulate a long-running Job
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
System.out.println(" run in a separate thread.");
});
2:supplyAsync(): if you want to return some result from your background task then use supplyAsync()
example:
// Run a task specified by a Supplier object asynchronously
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Result of the asynchronous computation";
}
});
3: thenApply():if you want to process and transform the result of a CompletableFuture when it arrives then use thenApply() method.
example:
// Create a CompletableFuture
CompletableFuture<String> whatsYourNameFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Raj";
});
// Attach a callback to the Future using thenApply()
CompletableFuture<String> greetingFuture = whatsYourNameFuture.thenApply(name -> {
return "Hello " + name;
});
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Harish Modi
Harish Modi is good in core java, advance java, springBoot. He is ASSOCIATE CONSULTANT - DEVELOPMENT. and Keen to learn new Skills.