Completable Future Start (Future) Continued
CompletableFuture
As shown in the figure, Completable Furure
is
It implements the Future
and CompletionStage
interfaces.
CompletionStage
is an interface introduced in Java 8.
CompletableFuture represents asynchronous processing and retains the result when it becomes available.
CompletableFuture
A Future that can be completed explicitly (by setting its value and status). Supports dependent functions and actions that occur upon completion and can be used as a Completion Stage. CompletableFuture@Oracle
This "support for dependent functions and actions that occur on completion" is a major feature of Completable Future
.
In addition to the feature of Future
," you will not have to wait for time-consuming processing "
You can do the following:
When the result of the process becomes available You can issue notifications and execute callbacks defined by lambda expressions and method references.
public Future<Double> getDoubleAsync(String variable){
//Create a Completable Future that holds the calculation results
CompletableFuture<Double> futureValue = new CompletableFuture<>();
new Thread( () -> { //Asynchronous execution of processing in another thread
try {
//Time-consuming process
double price = doSomeLongComputation(variable);
//Set the resulting value
futureValue.complete(price);
} catch (Exception ex) {
futureValue.completeExceptionally(ex);
}
}).start();
//Returns Future without waiting for calculation
return futureValue;
}
How to call the above method
//The return type is Future<Double>
Future<Double> futureValue = getDoubleAsync("test");
try {
//Call here. Blocked if value is not available
double value = futureValue.get();
System.out.printf("value is %.2f%n", value);
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
SupplyAsync
The CompletableFuture
class has multiple factory methods.
supplyAsync(Supplier supplier) Returns a new CompletableFuture in which the task running in ForkJoinPool.commonPool () calls the specified supplier and completes asynchronously using the value obtained. supplyAsync@Oracke
public static Future<Double> getDoubleAsyncHandy(String arg) {
return CompletableFuture.supplyAsync(() -> doSomeLongComputation(arg));
}
You can easily write CompletableFuture
as above by using the supplyAsync
method.
Recommended Posts