Summary of @async usage in spring

Source: Internet
Author: User

Introduction: In the Java application, in most cases, the interactive processing is done synchronously, but when dealing with the third-party system, it is prone to slow response, most of them use multithreading to accomplish this kind of task, in fact, after Spring 3.x, Has built-in @async to solve this problem perfectly, this article will complete the introduction of @async usage.

1. What is an asynchronous call?

Before interpreting the asynchronous invocation, let's take a look at the definition of the synchronous invocation, which is the entire processing sequence, when each process is executed and returns the result. An asynchronous invocation is simply a command that sends a call, and the caller does not have to wait for the called method to complete, but to proceed with the following process.

For example, in a call, you need to call the sequence A, B, C three procedure methods, such as they are synchronous calls, they need to be executed in sequence after the execution of the process, such as B is an asynchronous call method, after the completion of a, call B, do not wait for B to complete, but to execute the start call C, After C has been executed, it means that the process is complete.

2. General asynchronous invocation processing mode

In Java, when dealing with similar scenarios, it is based on the creation of independent threads to complete the corresponding asynchronous invocation logic, through the main thread and the execution flow between different threads, so that after starting a separate thread, the main thread continues execution without creating a stall wait.

3. @Async Introduction

In spring, the method based on the @async notation, called the Async method, will be executed in a separate thread, and the caller can continue other operations without waiting for it to complete.

How to enable @async in spring

Based on how Java configuration is enabled:

[HTML]View PlainCopy 
    1. @Configuration
    2. @EnableAsync
    3. public class Springasyncconfig {...}

Based on how the XML configuration file is enabled, configure the following:

[HTML]View PlainCopy 
    1. <task:executor id="Myexecutor" pool-size="5" />
    2. <task:annotation-driven executor="Myexecutor"/>

These are the two defining ways.

4. No return value calls based on @async

Examples are as follows:

[HTML]View PlainCopy 
    1. @Async//Label usage
    2. public void Asyncmethodwithvoidreturntype () {
    3. System.out.println ("Execute method asynchronously.")
    4. + Thread.CurrentThread (). GetName ());
    5. }

The way you use it is very simple, and a callout solves all the problems.

5. Calls based on the @async return value

Examples are as follows:

[HTML]View PlainCopy 
  1. @Async
  2. Public future<String> Asyncmethodwithreturntype () {
  3. System.out.println ("Execute Method Asynchronously-"
  4. + Thread.CurrentThread (). GetName ());
  5. try {
  6. Thread.Sleep (5000);
  7. return new AsyncResult<String> ("Hello World!!!!");
  8. } catch (Interruptedexception e) {
  9. //
  10. }
  11. return null;
  12. }

The above example shows that the data type returned is the future type, which is an interface. The specific result type is asyncresult, and this is where you need to be aware.

An example of an async method that invokes a result is returned:

[HTML]View PlainCopy 
  1. public void Testasyncannotationformethodswithreturntype ()
  2. Throws Interruptedexception, Executionexception {
  3. System.out.println ("invoking an asynchronous method.")
  4. + Thread.CurrentThread (). GetName ());
  5. Future<strings> Future = asyncannotationexample.asyncmethodwithreturntype ();
  6. while (true) {///This is used for loop judgment, waiting to get the result information
  7. if (Future.isdone ()) {//Determine if execution is complete
  8. System.out.println ("Result from Asynchronous process-" + future.get ());
  9. Break
  10. }
  11. System.out.println ("Continue doing something else.");
  12. Thread.Sleep (1000);
  13. }
  14. }

Analysis: These get the result information of the asynchronous method, it is by checking the state of the future to get the current asynchronous method is finished to implement.

6. Exception handling mechanism based on @async invocation

In an async method, if an exception occurs, it is not perceptible to the caller, caller. If you do need to do exception handling, proceed as follows:

1. Custom implementation of Asynctaskexecutor task executor

Here you define the logic and the way to handle specific exceptions.

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

Example Step 1, custom Taskexecutor

[HTML]View PlainCopy 
  1. public class Exceptionhandlingasynctaskexecutor implements Asynctaskexecutor {
  2. Private Asynctaskexecutor executor;
  3. Public Exceptionhandlingasynctaskexecutor (Asynctaskexecutor executor) {
  4. this.executor = executor;
  5. }
  6. Wrapped in a separate thread, @Async its essence.
  7. public void execute (Runnable task) {
  8. Executor.execute (createwrappedrunnable (Task));
  9. }
  10. public void execute (Runnable task, long Starttimeout) {
  11. /wrapped in a separate thread, @Async its essence
  12. Executor.execute (createwrappedrunnable (Task), starttimeout);
  13. }
  14. Public future Submit (Runnable Task) {return Executor.submit (createwrappedrunnable (Task));
  15. Wrapped in a separate thread, @Async its essence.
  16. }
  17. Public future submit (final callable Task) {
  18. Wrapped in a separate thread, @Async its essence.
  19. Return Executor.submit (createcallable (Task));
  20. }
  21. Private callable Createcallable (final callable Task) {
  22. return new callable () {
  23. Public T-Call () throws Exception {
  24. try {
  25. return Task.call ();
  26. } catch (Exception ex) {
  27. Handle (ex);
  28. Throw ex;
  29. }
  30. }
  31. };
  32. }
  33. Private Runnable createwrappedrunnable (final Runnable Task) {
  34. return new Runnable () {
  35. public void Run () {
  36. try {
  37. Task.run ();
  38. } catch (Exception ex) {
  39. Handle (ex);
  40. }
  41. }
  42. };
  43. }
  44. private void handle (Exception ex) {
  45. Where the specific exception logic is handled
  46. System.err.println ("Error during @Async execution:" + ex);
  47. }
  48. }


Analysis: It is possible to find that it implements the Asynctaskexecutor, with separate threads to perform the specific operation of each method. In Createcallable and createwrapperrunnable, the handling and mechanism of exceptions are defined.

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

Content in the configuration file:

[HTML]View PlainCopy 
  1. <task:annotation-driven executor="Exceptionhandlingtaskexecutor" scheduler=" Defaulttaskscheduler " />
  2. <Bean id= "exceptionhandlingtaskexecutor" class=" Nl.jborsje.blog.examples.ExceptionHandlingAsyncTaskExecutor ">
  3. <constructor-arg ref="Defaulttaskexecutor" />
  4. </Bean>
  5. <task:executor id="Defaulttaskexecutor" pool-size="5" />
  6. <task:scheduler id="Defaulttaskscheduler" pool-size="1" />

Analysis: The configuration here uses the custom taskexecutor to replace the default taskexecutor.

7. Transaction handling mechanism in @Async invocation

The method that is labeled in @async also applies to @transactional, and when it invokes a database operation, it cannot produce transaction management control because it is an asynchronous processing-based operation.

So how do you add transaction management to these operations? You can place methods that require transaction management operations inside an async method and add @transactional on the internally called method.

For example, method A, which is annotated with the @async/@Transactional, does not produce the purpose of transaction control.

Method B, using @async to annotate, B called C, d,c/d respectively using @transactional to do the labeling, you can achieve the purpose of transaction control.

8. Summary

Through the above description, the method and precautions should be used for @async.

@async Usage Summary in spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.