search
HomeJavajavaTutorialDetailed explanation of @Async usage in Spring and simple example introduction

This article mainly introduces the detailed explanation and simple examples of @Async usage in Spring. Friends in need can refer to

@Async usage in Spring

Introduction: In most Java applications, interaction processing is implemented through synchronization in most cases; however, when interacting with third-party systems, it is easy to cause slow response. In the past, most of them used multiple Threads are used to complete such tasks. In fact, after spring 3.x, @Async has been built in to perfectly solve this problem. This article will completely introduce the usage of @Async.

1. What is asynchronous call?

Before explaining asynchronous calls, let’s first look at the definition of synchronous calls; synchronization means that the entire processing process is executed sequentially, and when each process is completed, the results are returned. Asynchronous calls only send the calling instructions, and the caller does not need to wait for the called method to be completely executed; instead, it continues to execute the following process.

For example, in a certain call, three process methods A, B, and C need to be called sequentially; if they are all synchronous calls, they need to be executed sequentially before the process execution is completed. ; If B is an asynchronous calling method, after executing A, calling B does not wait for B to complete, but starts executing and calls C. After C is executed, it means that the process is completed.

2. Conventional asynchronous call processing method

In Java, when dealing with similar scenarios, it is usually based on creating independent threads to complete the corresponding Asynchronous calling logic passes the execution process between the main thread and different threads, so that after starting an independent thread, the main thread continues to execute without stalling and waiting.

3. Introduction to @Async

In Spring, methods based on @Async annotation are called asynchronous methods; when these methods are executed, they will Executed in a separate thread, the caller does not need to wait for its completion before continuing other operations.

How to enable @Async in Spring

Enabling method based on Java configuration:

@Configuration 
@EnableAsync 
public class SpringAsyncConfig { ... }

Based on XML configuration file The enabling method is configured as follows:

<task:executor id="myexecutor" pool-size="5" /> 
<task:annotation-driven executor="myexecutor"/>

The above are the two definition methods.

4. Based on @Async no return value call

The example is as follows:

@Async //标注使用 
public void asyncMethodWithVoidReturnType() { 
  System.out.println("Execute method asynchronously. " 
   + Thread.currentThread().getName()); 
}

The method used is very Simple, one label can solve all problems.

5. Call based on @Async return value

Examples are as follows:

@Async 
public Future<String> asyncMethodWithReturnType() { 
  System.out.println("Execute method asynchronously - " 
   + Thread.currentThread().getName()); 
  try { 
    Thread.sleep(5000); 
    return new AsyncResult<String>("hello world !!!!"); 
  } catch (InterruptedException e) { 
    // 
  } 
  
  return null; 
}

It can be found from the above example that the returned data type is Future type, which is an interface. The specific result type is AsyncResult, which needs attention.

Example of calling an asynchronous method that returns a result:

public void testAsyncAnnotationForMethodsWithReturnType() 
  throws InterruptedException, ExecutionException { 
  System.out.println("Invoking an asynchronous method. " 
   + Thread.currentThread().getName()); 
  Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType(); 
  
  while (true) { ///这里使用了循环判断,等待获取结果信息 
    if (future.isDone()) { //判断是否执行完毕 
      System.out.println("Result from asynchronous process - " + future.get()); 
      break; 
    } 
    System.out.println("Continue doing something else. "); 
    Thread.sleep(1000); 
  } 
}

Analysis: The result information of these asynchronous methods is obtained by continuously It is implemented by checking the status of Future to obtain whether the current asynchronous method has been executed.

6. Exception handling mechanism based on @Async calls

In an asynchronous method, if an exception occurs, it is impossible for the caller to Perceived. If exception handling is indeed required, handle it as follows:

1. Customize the task executor that implements AsyncTaskExecutor

Define the logic and method of handling specific exceptions here.

2. Configure a custom TaskExecutor to replace the built-in task executor

Example step 1, custom TaskExecutor

public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor { 
  private AsyncTaskExecutor executor; 
  public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) { 
    this.executor = executor; 
   } 
   ////用独立的线程来包装,@Async其本质就是如此 
  public void execute(Runnable task) {    
   executor.execute(createWrappedRunnable(task)); 
  } 
  public void execute(Runnable task, long startTimeout) { 
    /用独立的线程来包装,@Async其本质就是如此 
    executor.execute(createWrappedRunnable(task), startTimeout);      
  }  
  public Future submit(Runnable task) { return executor.submit(createWrappedRunnable(task)); 
    //用独立的线程来包装,@Async其本质就是如此。 
  }  
  public Future submit(final Callable task) { 
   //用独立的线程来包装,@Async其本质就是如此。 
    return executor.submit(createCallable(task));  
  }  
   
  private Callable createCallable(final Callable task) {  
    return new Callable() {  
      public T call() throws Exception {  
         try {  
           return task.call();  
         } catch (Exception ex) {  
           handle(ex);  
           throw ex;  
          }  
         }  
    };  
  } 
 
  private Runnable createWrappedRunnable(final Runnable task) {  
     return new Runnable() {  
       public void run() {  
         try { 
           task.run();  
         } catch (Exception ex) {  
           handle(ex);  
          }  
      } 
    };  
  }  
  private void handle(Exception ex) { 
   //具体的异常逻辑处理的地方 
   System.err.println("Error during @Async execution: " + ex); 
  } 
}

Analysis: It can be found that it implements AsyncTaskExecutor, using independent threads to perform specific method operations. In createCallable and createWrapperRunnable, the exception handling method and mechanism are defined.

handle() is where we need to focus on exception handling in the future.

Contents in the configuration file:

<task:annotation-driven executor="exceptionHandlingTaskExecutor" scheduler="defaultTaskScheduler" /> 
<bean id="exceptionHandlingTaskExecutor" class="nl.jborsje.blog.examples.ExceptionHandlingAsyncTaskExecutor"> 
  <constructor-arg ref="defaultTaskExecutor" /> 
</bean> 
<task:executor id="defaultTaskExecutor" pool-size="5" /> 
<task:scheduler id="defaultTaskScheduler" pool-size="1" />

Analysis: The configuration here uses a custom taskExecutor to replace the default TaskExecutor.

7. Transaction processing mechanism in @Async calls

The method marked with @Async is also marked with @Transactional; in it When a database operation is called, transaction management control will not be available because it is an operation based on asynchronous processing.

So how to add transaction management to these operations? Methods that require transaction management operations can be placed inside the asynchronous method, and @Transactional.

is added to the internally called method. For example: Method A is annotated with @Async/@Transactional, but a transaction cannot be generated. control purposes.

Method B is annotated with @Async. C and D are called in B. C/D are annotated with @Transactional respectively, which can achieve the purpose of transaction control.

8. Summary

Through the above description, we should know the methods and precautions for using @Async.

The above is a detailed explanation of the usage of @Async in Spring and a simple example introduction. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Spring怎么实现定时任务Java Spring怎么实现定时任务May 24, 2023 pm 01:28 PM

java实现定时任务Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor。Timer+TimerTask创建一个Timer就创建了一个线程,可以用来调度TimerTask任务Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线程。默认名字Timer-编号,默认不是守护线程。主要有三个比较重要的方法:cancel():终止任务调度,取消当前调度的所有任务,正在运行的任务不受影响purge():从任务队

Java axios与spring前后端分离传参规范是什么Java axios与spring前后端分离传参规范是什么May 03, 2023 pm 09:55 PM

一、@RequestParam注解对应的axios传参方法以下面的这段Springjava代码为例,接口使用POST协议,需要接受的参数分别是tsCode、indexCols、table。针对这个Spring的HTTP接口,axios该如何传参?有几种方法?我们来一一介绍。@PostMapping("/line")publicList

Spring Boot与Spring Cloud的区别与联系Spring Boot与Spring Cloud的区别与联系Jun 22, 2023 pm 06:25 PM

SpringBoot和SpringCloud都是SpringFramework的扩展,它们可以帮助开发人员更快地构建和部署微服务应用程序,但它们各自有不同的用途和功能。SpringBoot是一个快速构建Java应用的框架,使得开发人员可以更快地创建和部署基于Spring的应用程序。它提供了一个简单、易于理解的方式来构建独立的、可执行的Spring应用

Spring 最常用的 7 大类注解,史上最强整理!Spring 最常用的 7 大类注解,史上最强整理!Jul 26, 2023 pm 04:38 PM

随着技术的更新迭代,Java5.0开始支持注解。而作为java中的领军框架spring,自从更新了2.5版本之后也开始慢慢舍弃xml配置,更多使用注解来控制spring框架。

Java Spring框架创建项目与Bean的存储与读取实例分析Java Spring框架创建项目与Bean的存储与读取实例分析May 12, 2023 am 08:40 AM

1.Spring项目的创建1.1创建Maven项目第一步,创建Maven项目,Spring也是基于Maven的。1.2添加spring依赖第二步,在Maven项目中添加Spring的支持(spring-context,spring-beans)在pom.xml文件添加依赖项。org.springframeworkspring-context5.2.3.RELEASEorg.springframeworkspring-beans5.2.3.RELEASE刷新等待加载完成。1.3创建启动类第三步,创

从零开始学Spring Cloud从零开始学Spring CloudJun 22, 2023 am 08:11 AM

作为一名Java开发者,学习和使用Spring框架已经是一项必不可少的技能。而随着云计算和微服务的盛行,学习和使用SpringCloud成为了另一个必须要掌握的技能。SpringCloud是一个基于SpringBoot的用于快速构建分布式系统的开发工具集。它为开发者提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡和断路器等,使得开发者在构建微

Java Spring Bean生命周期管理的示例分析Java Spring Bean生命周期管理的示例分析Apr 18, 2023 am 09:13 AM

SpringBean的生命周期管理一、SpringBean的生命周期通过以下方式来指定Bean的初始化和销毁方法,当Bean为单例时,Bean归Spring容器管理,Spring容器关闭,就会调用Bean的销毁方法当Bean为多例时,Bean不归Spring容器管理,Spring容器关闭,不会调用Bean的销毁方法二、通过@Bean的参数(initMethod,destroyMethod)指定Bean的初始化和销毁方法1、项目结构2、PersonpublicclassPerson{publicP

spring设计模式有哪些spring设计模式有哪些Dec 29, 2023 pm 03:42 PM

spring设计模式有:1、依赖注入和控制反转;2、工厂模式;3、模板模式;4、观察者模式;5、装饰者模式;6、单例模式;7、策略模式和适配器模式等。详细介绍:1、依赖注入和控制反转: 这两个设计模式是Spring框架的核心。通过依赖注入,Spring负责管理和注入组件之间的依赖关系,降低了组件之间的耦合度。控制反转则是指将对象的创建和依赖关系的管理交给Spring容器等等。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft