Java @Async Explained: Usage Guide

In Java, the @Async annotation is used to mark a method as one that should be executed asynchronously. When the @Async annotation is added to a method, that method will be executed asynchronously in a separate thread, without blocking the current thread.

The following conditions need to be met in order to use the @Async annotation:

  1. Add the @EnableAsync annotation on the configuration class of the application to enable support for asynchronous methods.
  2. Add the @Async annotation on the method that needs to be executed asynchronously.

Here is an example using the @Async annotation:

@EnableAsync
@Configuration
public class AppConfig {
   // 配置异步执行器
   @Bean(name = "taskExecutor")
   public Executor taskExecutor() {
      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
      executor.setCorePoolSize(10);
      executor.setMaxPoolSize(10);
      executor.setQueueCapacity(500);
      executor.setThreadNamePrefix("MyAsyncThread-");
      executor.initialize();
      return executor;
   }
}

@Service
public class MyService {
   @Async("taskExecutor")
   public void asyncMethod() {
      // 异步执行的方法体
   }
}

In the above example, the @EnableAsync annotation enables support for asynchronous methods. The @Async annotation is added to the asyncMethod method in the MyService class, specifying the asynchronous executor to be used (specified by the name “taskExecutor”). When calling the asyncMethod method, it will be executed asynchronously in a separate thread.

It is important to note that asynchronous methods should not be called within the same class, as doing so will be interpreted as a regular synchronous method call. It is best to place asynchronous methods in a separate class or service, and call them where needed through dependency injection.

bannerAds