Asynchronous processing @Async

@Async In Java applications, in most cases, interactive processing is achieved through synchronization; but when dealing with third-party systems, it is easy to cause slow response. Most of the previous ones used multithreading To complete such tasks, in fact, after Spring 3.x, @Async has been built in to perfectly solve this problem. This article will introduce the usage of @Async.

1. What is an asynchronous call?

    Before explaining asynchronous calls, let's first look at the definition of synchronous calls; synchronization is the sequential execution of the entire processing process, and when each process is completed, the result is returned. An asynchronous call just sends the call instruction, 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, the 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 they are counted as the completion of the process; if B is an asynchronous The call method, after executing A, call B, and do not wait for B to complete, but start to call C. After C is executed, it means that the process is completed.

2. Conventional asynchronous call processing methods

    in Java, generally when dealing with similar scenarios, it is based on creating independent threads to complete the corresponding asynchronous call logic, through the execution process between the main thread and different threads, thus After starting a separate thread, the main thread continues execution without stalling.

3. @Async introduction

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




7. Transaction processing mechanism in @Async call

    The method marked with @Async is also marked with @Transactional; when it calls the database operation, it will not be able to control the transaction management because it is based on asynchronous processing.

     So how do you add transaction management to these operations? You can place the method that requires transaction management operations inside the asynchronous method, and add @Transactional to the method that is called inside.

    For example: Method A is marked with @Async/@Transactional, but it cannot achieve the purpose of transaction control.

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

8. Summary

     Through the above description, the methods and precautions for @Async should be used.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327033824&siteId=291194637