Java asynchronous programming

Eternal clouds 2020-11-09 12:33:13
java asynchronous programming


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

thenApplyAsyncthenAcceptAsync 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

版权声明
本文为[Eternal clouds]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云