目录
- 注释
- 源码
应用见
SpringBoot:详解@EnableAsync + @Async 实现共享线程池
源码解析见
@EnableAsync 详解,@Async 如何生效
学习注解,从注释和源码入手
注释
部分关键注释,我自己标注了一些中文注释便于理解:
注解想要被设置成异步的方法
/**
* Annotation that marks a method as a candidate for <i>asynchronous</i> execution.
* Can also be used at the type level, in which case all of the type's methods are
* considered as asynchronous.
*
* <p>In terms of target method signatures, any parameter types are supported.
* However, the return type is constrained to either {@code void} or
* {@link }. In the latter case, you may declare the
* more specific {@link } or
* {@link } types which allow for richer
* interaction with the asynchronous task and for immediate composition with
* further processing steps.
*
* <p>A {@code Future} handle returned from the proxy will be an actual asynchronous
* {@code Future} that can be used to track the result of the asynchronous method
* execution. However, since the target method needs to implement the same signature,
* it will have to return a temporary {@code Future} handle that just passes a value
* through: . Spring's {@link AsyncResult}, EJB 3.1's {@link },
* or {@link #completedFuture(Object)}.
源码
- 三个元注解,没什么好说的
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Async {
- 可以执行运行被注解方法的线程池
一般来说开发者要实现AsyncConfigurer接口,自己提供线程池和异常处理器,实际开发中也可以不实现此接口,在配置类中的方法(如命名方法为asyncServiceExecutor)加上@Bean注解,在调用的方法上使用@Async(“asyncServiceExecutor”),来指定运行此方法的线程池
/**
* A qualifier value for the specified asynchronous operation(s).
* <p>May be used to determine the target executor to be used when executing this
* method, matching the qualifier value (or the bean name) of a specific
* {@link Executor} or
* {@link TaskExecutor}
* bean definition.
* <p>When specified on a class level {@code @Async} annotation, indicates that the
* given executor should be used for all methods within the class. Method level use
* of {@code Async#value} always overrides any value set at the class level.
* @since 3.1.2
*/
String value() default "";