1
-
2
-
3
- - [ ] [ ** Future vs. CompletableFuture** ] ( https://blog.knoldus.com/future-vs-completablefuture-1/ )
4
- - [ ] 源代码分析
1
+ > 本文已经收录自 springboot-guide : [ https://github.com/Snailclimb/springboot-guide ] ( https://github.com/Snailclimb/springboot-guide ) (Spring Boot 核心知识点整理。 基于 Spring Boot 2.19+。)
5
2
6
3
# 新手也能看懂的 SpringBoot 异步编程指南
7
4
@@ -31,7 +28,7 @@ Future 模式的核心思想是 **异步调用** 。当我们执行一个方法
31
28
32
29
很多人对于 TaskExecutor 不是太了解,所以我们花一点篇幅先介绍一下这个东西。从名字就能看出它是任务的执行者,它领导执行着线程来处理任务,就像司令官一样,而我们的线程就好比一只只军队一样,这些军队可以异步对敌人进行打击👊。
33
30
34
- Spring 提供了` TaskExecutor ` 接口作为任务执行者的抽象,它和` java.util.concurrent ` 包下的` Executor ` 接口很像。稍微不同的 ` TaskExecutor ` 接口用到了 Java 8 的语法` @FunctionalInterface ` 声明这个借口是一个函数式接口 。
31
+ Spring 提供了` TaskExecutor ` 接口作为任务执行者的抽象,它和` java.util.concurrent ` 包下的` Executor ` 接口很像。稍微不同的 ` TaskExecutor ` 接口用到了 Java 8 的语法` @FunctionalInterface ` 声明这个接口是一个函数式接口 。
35
32
36
33
` org.springframework.core.task.TaskExecutor `
37
34
@@ -94,7 +91,7 @@ public class AsyncConfig implements AsyncConfigurer {
94
91
95
92
** 如果队列已满并且当前同时运行的线程数达到最大线程数的时候,如果再有新任务过来会发生什么呢?**
96
93
97
- Spring 默认使用的是 ` hreadPoolExecutor .AbortPolicy` 。在Spring的默认情况下,` ThreadPoolExecutor ` 将抛出 ` RejectedExecutionException ` 来拒绝新来的任务 ,这代表你将丢失对这个任务的处理。 对于可伸缩的应用程序,建议使用 ` ThreadPoolExecutor.CallerRunsPolicy ` 。当最大池被填满时,此策略为我们提供可伸缩队列。
94
+ Spring 默认使用的是 ` ThreadPoolExecutor .AbortPolicy` 。在Spring的默认情况下,` ThreadPoolExecutor ` 将抛出 ` RejectedExecutionException ` 来拒绝新来的任务 ,这代表你将丢失对这个任务的处理。 对于可伸缩的应用程序,建议使用 ` ThreadPoolExecutor.CallerRunsPolicy ` 。当最大池被填满时,此策略为我们提供可伸缩队列。
98
95
99
96
** ` ThreadPoolTaskExecutor ` 饱和策略定义:**
100
97
@@ -103,7 +100,7 @@ public class AsyncConfig implements AsyncConfigurer {
103
100
- ** ThreadPoolExecutor.AbortPolicy** :抛出 ` RejectedExecutionException ` 来拒绝新任务的处理。
104
101
- ** ThreadPoolExecutor.CallerRunsPolicy** :调用执行自己的线程运行任务。您不会任务请求。但是这种策略会降低对于新任务提交速度,影响程序的整体性能。另外,这个策略喜欢增加队列容量。如果您的应用程序可以承受此延迟并且你不能任务丢弃任何一个任务请求的话,你可以选择这个策略。
105
102
- ** ThreadPoolExecutor.DiscardPolicy:** 不处理新任务,直接丢弃掉。
106
- - ** ThreadPoolExecutor.DiscardOldestPolicy:** 此策略将丢弃最早的未处理的任务请求。
103
+ - ** ThreadPoolExecutor.DiscardOldestPolicy:** 此策略将丢弃最早的未处理的任务请求。
107
104
108
105
### 2. 编写一个异步的方法
109
106
@@ -262,6 +259,11 @@ Elapsed time: 0
262
259
263
260
可以看到系统会直接返回给用户结果,然后系统才真正开始执行任务。
264
261
262
+ ## 待办
263
+
264
+ - [ ] [ ** Future vs. CompletableFuture** ] ( https://blog.knoldus.com/future-vs-completablefuture-1/ )
265
+ - [ ] 源代码分析
266
+
265
267
## Reference
266
268
267
269
- https://spring.io/guides/gs/async-method/
0 commit comments