[JAVA] CompletableFuture Getting Started 2 (Try to make CompletableFuture)

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.

What is different from Future?

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.

Basic usage

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);
}

When using 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

CompletableFuture Getting Started 2 (Try to make CompletableFuture)
CompletableFuture Getting Started 3 (Try issuing an asynchronous request)
Try to make a simple callback
Try to make a peepable iterator
Interface Try to make Java problem TypeScript 7-3
Increment behavior Try to make Java problem TypeScript 3-4
String operation Try to make Java problem TypeScript 9-3
Getting started with Kotlin to send to Java developers
Try to make a music player using Basic Player
Getting Started with Doma-Introduction to the Criteria API
Try to release gem
Initialization of for Try to make Java problem TypeScript 5-4
Getting Started with DBUnit
Getting Started with Ruby
Try to make an addition program in several languages
How to make shaded-jar
Getting Started with Swift
Getting Started with Docker
Getting Started with Doma-Transactions
[Beginner] Try to make a simple RPG game with Java ①
[swift5] Try to make an API client with various methods
Getting Started with Doma-Annotation Processing
Getting Started with Java Collection
Try Spring Boot from 0 to 100.
Java --How to make JTable
To make heavy queries asynchronously
Getting Started with JSP & Servlet
Completable Future Getting Started (First Future)
Getting Started with Java Basics
Getting Started with Spring Boot
[Rails] How to make seed
Getting Started with Ruby Modules
Returning to the beginning, getting started with Java ② Control statements, loop statements
Try to make a cross-platform application with JRuby (jar file generation)
Try to make a CS 3D tile from the Geographical Survey tile