@Async 详解

Posted oxye

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@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 java.util.concurrent.Future}. In the latter case, you may declare the
 * more specific {@link org.springframework.util.concurrent.ListenableFuture} or
 * {@link java.util.concurrent.CompletableFuture} 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: e.g. Spring‘s {@link AsyncResult}, EJB 3.1‘s {@link javax.ejb.AsyncResult},
 * or {@link java.util.concurrent.CompletableFuture#completedFuture(Object)}.

源码

  1. 三个元注解,没什么好说的
	@Target({ElementType.METHOD, ElementType.TYPE})
	@Retention(RetentionPolicy.RUNTIME)
	@Documented
	public @interface Async {
  1. 可以执行运行被注解方法的线程池

一般来说开发者要实现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 java.util.concurrent.Executor Executor} or
	 * {@link org.springframework.core.task.TaskExecutor 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 "";

以上是关于@Async 详解的主要内容,如果未能解决你的问题,请参考以下文章

Swift 中的 async/await ——代码实例详解

async/await使用深入详解

详解 js中的async和await

C# 中的Async 和 Await 的用法详解

如何在async.race函数中使用async.retry

(转) Java中的负数及基本类型的转型详解