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() {
@Override
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() {
@Override
public void run() {
}
},executor);
// Create a task with a return value .
CompletableFuture f2 = CompletableFuture.supplyAsync(new Supplier() {
@Override
public String get() {
// Business logic
return null;
}
},executor);
-
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 .
-
Created CompletableFuture After object , Automatically and asynchronously runnable.run() 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 .
Serial
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 》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 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”) //②
.thenApply(String::toUpperCase);//③
System.out.println(f0.join());
// 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”;
System.out.println(s);
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.
https://en.cdmana.com/2022/01/202201270233115108.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command