Preface
stay java You don't know about asynchronous programming ,crud No problem at all , But there are requirements that you can't achieve gracefully .
js There's also asynchronous programming , When you understand how to write asynchronous code in a synchronous way , I believe that you have further attainments in programming .
Most people are chasing micro Services , Maybe they just use Ribbon
and Feign
. Microservices are an architectural choice , When you don't reach the architecture level , I think you should pay more attention to business coding , In other words, the writing of single service code in microservices .
Single service performance is extremely poor , The overall performance of your microservices is not much better , Only by limiting the current 、 Fuse plus multiple deployment machines to solve the problem of low concurrency . Before you want to play microservices , After playing concurrency, consider high concurrency . The first java in juc The concurrency related knowledge under the package is clear and clear, and then proceed to the next step , It won't take much time . Microservices are what you learn after you upgrade .
I was going to continue to write Mysql, But I can't really mention my interest ( You need to read books and study , It's a black box study after all ), I have to finish the task with this article .
The content of this article is
- js in Promise and async await A column of
- SpringBoot Asynchronous programming in
- Future
- CompletableFuture
js Asynchronous programming
Get used to using Promise , Avoid putting fn Pass it as a parameter , Avoid going back to hell . It's not just api Call question , This is a change in your programming thinking .
const awaitFunc = function _awaitFunc() {
return Promise.resolve('awaitFunc').then(data => {
console.log(data);
return 'awaitFunc-then-return-data';
});
};
const async = async function _async() {
setTimeout(() => {
console.log(' Verify that the macro task queue is added ---1');
}, 0);
// Add do not add await What's the difference? ?
await awaitFunc().then(data => {
console.log(data);
setTimeout(() => {
console.log(' Verify that the macro task queue is added ---2');
}, 0);
});
console.log('awaitFunc Print after execution ');
};
async();
SpringBoot Asynchronous programming in
stay SpringBoot @EnableAsync
and @Async
Can help you with asynchronous programming . The underlying principle is ThreadPoolExecutor
and Future
Encapsulation .
<img src="http://oss.mflyyou.cn/blog/20201108120510.png?author=zhangpanqin" alt="1583165-20200710095540896-1284477865" style="zoom: 33%;" />
Let's take this boiling water for example , When you synchronize serial execution , Need to consume 20 minute . Synchronous programming thinking model is simpler , Easy to implement .
When you're multithreaded and asynchronous , Just consume 16 minute . The asynchronous programming mindset is a little more complex , Asynchronous to synchronous communication between multithreads is a challenge .
@GetMapping("/tea/async")
public RetUtil makeTeaAsync() throws InterruptedException, ExecutionException {
// Stopwatch Used to calculate code execution time
final Stopwatch started = Stopwatch.createStarted();
final Future asyncResult = makeTeaService.boilWater();
final Future asyncResult1 = makeTeaService.washTeaCup();
asyncResult.get();
asyncResult1.get();
final long elapsed = started.elapsed(TimeUnit.SECONDS);
String str = StrUtil.format(" The task was carried out {} second ", elapsed);
final MakeTeaVO makeTeaVO = new MakeTeaVO();
makeTeaVO.setMessage(str);
return RetUtil.success(makeTeaVO);
}
@Service
public class IMakeTeaServiceImpl implements IMakeTeaService {
@Override
@Async
public AsyncResult<String> boilWater() throws InterruptedException {
System.out.println(" Wash the kettle ");
TimeUnit.SECONDS.sleep(1);
System.out.println(" The boiling water ");
TimeUnit.SECONDS.sleep(15);
return new AsyncResult(" Wash the kettle -> The boiling water ");
}
@Override
@Async
public AsyncResult<String> washTeaCup() throws InterruptedException {
System.out.println(" Wash tea cups ");
System.out.println(" Wash the teapot ");
System.out.println(" Take the tea ");
TimeUnit.SECONDS.sleep(4);
return new AsyncResult(" Wash tea cups , Wash the teapot , Take the tea ");
}
}
AsyncResult
yes Future
Implementation class of , When calling Future.get
Will block waiting for results to return .@Async
You can also specify which thread pool to execute tasks in .
final Future asyncResult = makeTeaService.boilWater();
final Future asyncResult1 = makeTeaService.washTeaCup();
asyncResult.get();
asyncResult1.get();
This Demo The implementation of the , Need to call twice Furute.get() It's not elegant .
@Override
public String makeTea() throws InterruptedException {
final CountDownLatch count = new CountDownLatch(2);
THREAD_POOL_EXECUTOR.execute(() -> {
System.out.println(" Wash the kettle ");
System.out.println(" The boiling water ");
try {
TimeUnit.SECONDS.sleep(16);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
count.countDown();
}
});
THREAD_POOL_EXECUTOR.execute(() -> {
System.out.println(" Wash tea cups ");
System.out.println(" Wash the teapot ");
System.out.println(" Take the tea ");
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
count.countDown();
}
});
count.await();
System.out.println(" Make tea ");
return "";
}
@GetMapping("/tea/async2")
public RetUtil makeTeaAsync2() throws InterruptedException, ExecutionException {
final Stopwatch started = Stopwatch.createStarted();
makeTeaService.makeTea();
final long elapsed = started.elapsed(TimeUnit.SECONDS);
String str = StrUtil.format(" The task was carried out {} second ", elapsed);
final MakeTeaVO makeTeaVO = new MakeTeaVO();
makeTeaVO.setMessage(str);
return RetUtil.success(makeTeaVO);
}
Use CountDownLatch
Convert asynchronous code to synchronous return , This is just another implementation
Future
public interface Future<V> {
/**
* Try to cancel the task .
* If the task is completed , call cancel return false.
* If the mission has been canceled , call cancel And will return to false
*
* If the task has been carried out , mayInterruptIfRunning Indicates whether the thread executing the task is interrupted .
* mayInterruptIfRunning by true Will trigger thread interrupt ( When threads sleep , It throws an exception InterruptedException),
* by false Do not interrupt task execution , Only change Future The state of
*
* Called cancel Method , call get The method throws an exception
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* The task is called before cancel , This method returns true
*/
boolean isCancelled();
/**
* Finish the task and return to true
*/
boolean isDone();
/**
* Waiting for the task to complete , Then return its result
* @return the computed result
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted while waiting
*/
V get() throws InterruptedException, ExecutionException;
/**
* Waiting for the task to complete , Then return its result . Timeout did not return , Throw an exception TimeoutException
*/
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
Future.cancel(true)
Interrupt that triggers thread hibernation , namely TimeUnit.SECONDS.sleep(10);
It throws an exception .
Future.cancel(true)
perhaps Future.cancel(false)
Will trigger Future.get()
abnormal .
public static void main(String[] args) throws ExecutionException, InterruptedException {
final Future<String> submit = THREAD_POOL_EXECUTOR.submit(() -> {
System.out.println(" The task begins ");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" Task completed ");
return "ok";
});
THREAD_POOL_EXECUTOR.execute(() -> {
System.out.println(" perform submit.cancel");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
submit.cancel(false);
});
// submit.get();
System.out.println(" The whole process is finished ");
}
JDK Provide Future
The implementation of the FutureTask
The source code is relatively simple , Don't expand .
CompletableFuture
because Future
Limitations of use : Cannot chain call 、 The results of multiple asynchronous calculations cannot be passed on to the next asynchronous task ( It can be done , But programming is a little more complicated ), Asynchronously performs exception capture processing
from JDK 1.8
Start , bosses Doug Lea
Brings an easier asynchronous programming model ,CompletableFuture.
CompletableFuture It can be done
1、 Get the result of asynchronous execution and chain it to the next asynchronous execution
2、 Asynchronous execution , You have a chance to handle exceptions that occur during asynchronous execution
All in all ,CompletableFuture
I really want to .
CompletableFuture
The implementation is more complex , Some places are not so easy to understand , When you understand the realization idea , You're a foot into responsive programming .
appetizers
public class CompletableFutureBlog1 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
final Stopwatch started = Stopwatch.createStarted();
// Wash the kettle , Boil water
CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(() -> {
System.out.println(" Wash the kettle ");
System.out.println(" Boil water ");
try {
TimeUnit.SECONDS.sleep(16);
} catch (InterruptedException e) {
e.printStackTrace();
}
return " Wash the kettle -> Boil water ";
});
// Wash the teapot , Wash tea cups -> Take the tea
CompletableFuture<String> completableFuture2 =
CompletableFuture.supplyAsync(() -> {
System.out.println(" Wash the teapot ");
System.out.println(" Wash tea cups ");
System.out.println(" Take the tea ");
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
return " Wash the teapot , Wash tea cups -> Take the tea ";
});
// The result of combining the two asynchronous operations , Pass to method calculation
final CompletableFuture<String> completableFuture = completableFuture2.thenCombine(completableFuture1, (result2, result1) -> {
System.out.println(StrUtil.format("result2 yes Wash the teapot , Wash tea cups -> Take the tea : {}", result2));
System.out.println(StrUtil.format("result1 yes Wash the kettle -> Boil water : {}", result1));
System.out.println(" Make tea ");
return " Make tea ";
});
completableFuture.get();
System.out.println(" execution time : " + started.elapsed(TimeUnit.SECONDS));
}
}
runAsync and supplyAsync The difference between
runAsync
and supplyAsync
The difference is whether you need to get the results of asynchronous computation . When you need to process the results asynchronously , You need supplyAsync
public class CompletableFutureBlog2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
final Stopwatch started = Stopwatch.createStarted();
final CompletableFuture<Integer> ret = CompletableFuture.supplyAsync(() -> {
System.out.println(" Start time-consuming asynchronous computing , Consume 3 second ");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
final Integer integer = ret.get();
System.out.println(StrUtil.format(" The result of asynchronous execution : {}", integer));
System.out.println(" execution time : " + started.elapsed(TimeUnit.SECONDS));
}
}
thenApplyAsync
、thenAcceptAsync
and thenRunAsync
thenXX
All for execution after the end of the last asynchronous calculation .
We divide the results of asynchronous computation into the following situations :
- Need to rely on the results of asynchronous computation , And depending on the result of asynchronous calculation, the calculation returns another result
thenApplyAsync
- Rely on the results of asynchronous computation , But it won't produce new results ,
thenAcceptAsync
- It doesn't depend on the result of calculation , And no value is returned
thenRunAsync
public class CompletableFutureBlog3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
final Stopwatch started = Stopwatch.createStarted();
final CompletableFuture<Integer> ret = CompletableFuture.supplyAsync(() -> {
System.out.println(" Start time-consuming asynchronous computing , Consume 3 second ");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
final Integer result = ret.thenApplyAsync(data -> {
System.out.println(" Depending on the last asynchronous computation , Consume 5 second ");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return data + 12;
}).get();
System.out.println(StrUtil.format(" The result of asynchronous execution : {}", result));
System.out.println(" execution time : " + started.elapsed(TimeUnit.SECONDS));
}
}
thenCombineAsync
Combine another CompletableFuture
Asynchronous computation , When two asynchronous calculations are finished , Execution callback .
Calculating a time-consuming calculation . Split this time-consuming calculation into two time-consuming asynchronous calculations , When two asynchronous calculations end , At the end of the merger
public class CompletableFutureBlog4 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
final Stopwatch started = Stopwatch.createStarted();
final CompletableFuture<Integer> ret1 = CompletableFuture.supplyAsync(() -> {
System.out.println(" Start time-consuming asynchronous computing , Consume 3 second ");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
final CompletableFuture<Integer> ret2 = CompletableFuture.supplyAsync(() -> {
System.out.println(" Start time-consuming asynchronous computing , Consume 5 second ");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
final CompletableFuture<Integer> integerCompletableFuture = ret2.thenCombineAsync(ret1, (result1, result2) -> result1 + result2);
final Integer result = integerCompletableFuture.get();
System.out.println(StrUtil.format(" The result of asynchronous execution : {}", result));
System.out.println(" execution time : " + started.elapsed(TimeUnit.SECONDS));
}
}
allOf
and anyOf
Can combine multiple CompletableFuture
, When each CompletableFuture
It's all done , Follow up logic .
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
return andTree(cfs, 0, cfs.length - 1);
}
Can combine multiple CompletableFuture
, When any one CompletableFuture
It's all done , Follow up logic .
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
return orTree(cfs, 0, cfs.length - 1);
}
future,future2,future3 After execution , Then execute the following logic .
public class CompletableFutureBlog5 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
final Stopwatch started = Stopwatch.createStarted();
final CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(1);
});
final CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(1);
});
final CompletableFuture<Void> future3 = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(1);
});
final CompletableFuture<Void> future1 = CompletableFuture.allOf(future3, future2, future);
future1.get();
System.out.println(" execution time : " + started.elapsed(TimeUnit.SECONDS));
}
}
Put the above demo in allOf Replace with anyOf, When any CompletableFuture completion of enforcement ,future1.get();
It will return the result .
Other ways to look at parameters and comments will learn . I will not list them one by one .
When used , Consider whether or not to rely on the results of asynchronous computation , Do you want to handle exceptions , Do you want to return a new asynchronous calculation result , We can know which one to choose from these aspects api 了 .
This paper is written by Zhang Panqin's blog http://www.mflyyou.cn/ A literary creation . Reprint freely 、 quote , But you need to sign the author and indicate the source of the article .For example, the official account of WeChat , Please add the author's official account number 2 . WeChat official account name :Mflyyou