current position:Home>Completable future asynchronous programming, clear understanding of Java Baidu cloud resources

Completable future asynchronous programming, clear understanding of Java Baidu cloud resources

2022-01-27 02:33:12 Alibaba_ Open Source

public void run() {

// Business logic




  • Create a task with a return value .


CompletableFuture f2 = CompletableFuture.supplyAsync(new Supplier() {


public String get() {

// Business logic

return null;



Mode two : Use custom thread pool ( It is recommended to use )

// Creating a thread pool

ExecutorService executor = Executors.newFixedThreadPool(10);

// Create a task with no return value .

CompletableFuture f1 = CompletableFuture.runAsync(new Runnable() {


public void run() {



// Create a task with a return value .

CompletableFuture f2 = CompletableFuture.supplyAsync(new Supplier() {


public String get() {

// Business logic

return null;



  1. By default CompletableFuture Will use public ForkJoinPool Thread pool , The default number of threads created by this thread pool is CPU Of Check the number ( It can also be done through JVM option:-Djava.util.concurrent.ForkJoinPool.common.parallelism To set up ForkJoinPool Number of threads in the thread pool ). If all CompletableFuture Share a thread pool , So once there's a task to perform some very slow I/O fuck do , Will cause all threads in the thread pool to block in I/O Operationally , This causes thread starvation , And then affect the performance of the whole system . therefore , It is strongly recommended that you Create different thread pools according to different business types , To avoid interfering with each other .

  2. Created CompletableFuture After object , Automatically and asynchronously Methods or supplier.get() Method . because CompletableFuture Class implements the Future Interface , So you can pass both questions Future Interface to solve . in addition ,CompletableFuture Class also implements CompletionStage Interface .

Commonly used API

  • public T get(): Get calculation results , The blocking method will wait for the calculation result to be completed .

  • public T get(long timeout,TimeUnit unit): Blocking methods with time constraints

  • public T getNow(T valueIfAbsent) Get method results immediately , If there is no end of calculation, the returned value

  • public T join() and get() Method is similar to the active blocking thread , Wait for the calculation result . and get() There are subtle differences in approach .

  • public boolean complete(T value): Complete the calculation immediately , And set the result to the value passed , Return whether the setting is successful

  • public boolean completeExceptionally(Throwable ex): Complete the calculation immediately , And throw an exception

understand CompletionStage Interface

CompletionStage The interface can clearly describe the temporal relationship between tasks , Timing relationship : Serial , parallel , Converge .


The execution order between threads is serial .

//Async Represents asynchronous execution fn

CompletionStage thenApply(fn);

CompletionStage thenApplyAsync(fn);

CompletionStage thenAccept(consumer);

CompletionStage thenAcceptAsync(consumer);

CompletionStage thenRun(action);

CompletionStage thenRunAsync(action);

CompletionStage thenCompose(fn);

CompletionStage thenComposeAsync(fn);

  • CompletionStage The serial relationship is described in the interface , Mainly thenApply、thenAccept、thenRun and thenCompose These four A series of interfaces .

  • thenApply Parameters in series functions fn The type of is interface Function<T,R>, This interface is connected with CompletionStage The relevant method is R apply(T t), This method It can receive parameters as well as return values , therefore thenApply The series method returns CompletionStage.

  • and thenAccept Parameters in the series method consumer The type of is interface Consumer, This interface is connected with CompletionStage relevant Approach is to voidaccept(T t), This method, though Support parameters , But it doesn't support return value , therefore thenAccept The series method returns CompletionStage.

  • thenRun In the series method a

《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》

【】 Full content open source sharing

ction The parameter is Runnable, therefore action Both Parameters cannot be received and return values are not supported , therefore thenRun The series of methods also returns CompletionStage.

  • In these methods Async Represents asynchronous execution fn、consumer perhaps action. among , What needs your attention is thenCompose Series method , This series of methods will create a new sub process , The end result and thenApply The series is the same .

Demo serial

//supplyAsync() Start an asynchronous technological process

CompletableFuture f0 = CompletableFuture.supplyAsync(

() -> “Hello World”) //①

.thenApply(s -> s “girl”) //②



// Output results HELLO WORLD girl

Although this is an asynchronous process , But the task ①②③ nevertheless Serial execution ,② rely on ① The results of the implementation of ,③ rely on ② The results of the implementation of .

AND Converge

CompletionStage The interface describes AND Convergence , Mainly thenCombine、thenAcceptBoth and runAfterBoth Serial interface , The difference between these interfaces also comes from fn、consumer、action These three core parameters are different .

CompletionStage thenCombine(other,fn);

CompletionStage thenCombineAsync(other,fn);

CompletionStage thenAcceptBoth(other,consumer); CompletionStage thenAcceptBothAsync(other,consumer); CompletionStage runAfterBoth(other, action);

CompletionStage runAfterBothAsync(other, action);

demonstration :

// Start an asynchronous process f1

CompletableFuture f1 = CompletableFuture.runAsync(()->{

System.out.println(“ Asynchronous task -1”);


// Start an asynchronous process f2

CompletableFuture f2 = CompletableFuture.supplyAsync(()->{

String s = “ Asynchronous task -2”;


return s;


// Start a convergence process f3

CompletableFuture f3 = f1.thenCombine(f2,(a,tf)->{

return tf;//tf yes f2 Value


copyright notice
author[Alibaba_ Open Source],Please bring the original link to reprint, thank you.

Random recommended