Springboot asynchronous threading Simple three styles

Source: Internet
Author: User

References: In Java applications, in most cases, the interaction is done synchronously, but when dealing with third-party systems, it is prone to slow response times, most of which are done with multithreading, 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.

One, asynchronous invocation without parameters

@Override    @Async public    String Asyncmethodwithvoidreturntype () {        System.out.println ("Thread Name:" + Thread.CurrentThread (). GetName () + "be ready to read data!");        try {            thread.sleep (5);            System.out.println (Thread.CurrentThread (). GetName () + "---------------------" without a return value delay of 5 seconds: ");        } catch (Interruptedexception e) {            e.printstacktrace ();        } for        (int i =0; i<100000000;i++) {//            System.out.println ("Execute method Asynchronously.-----------------------"+//                    "--"+ Thread.CurrentThread (). GetName () +i);/        }        return "entered into async";    }

Second, asynchronous call with parameters asynchronous method can pass in Parameters

  @Async public    void Asyncinvokewithparameter (String s) {        log.info ("Asyncinvokewithparameter, parementer={}", s);        throw new IllegalArgumentException (s);    }

Iii. calling an asynchronous thread that returns a future

@Async public    future<string> asyncinvokereturnfuture (int i) {        log.info ("Asyncinvokereturnfuture, parementer={} ", i);        Future<string> future;        try {            Thread.Sleep (4);            Future = new Asyncresult<string> ("Success:" + i);        } catch (Interruptedexception e) {Future            = new Asyncresult<string> ("error");        }        return to the future;    }

The above call returns the async thread of the future, and the data type returned is the future type, which is an interface. The specific result type is asyncresult.

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

           multi-threaded future        future<string> = Mainservice.asyncinvokereturnfuture (+);        Future anomaly capture         System.out.println ("Future delay 3 seconds:" +future.get ());

Result: The results of these methods are obtained by checking the state of the future to see if the current async method is executed.

Iv. 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

    public class Exceptionhandlingasynctaskexecutor implements Asynctaskexecutor {private Asynctaskexecutor exec          Utor;           Public Exceptionhandlingasynctaskexecutor (Asynctaskexecutor executor) {this.executor = executor; }////is wrapped in a separate thread, @Async its nature is so public void execute (Runnable task) {Executor.execute (CR          Eatewrappedrunnable (Task)); The public void execute (Runnable task, long starttimeout) {/wrapped with a separate thread, @Async its nature is so EXECU                   Tor.execute (createwrappedrunnable (Task), starttimeout);             } Public Future Submit (Runnable Task) {return Executor.submit (createwrappedrunnable (Task));          Wrapped in a separate thread, @Async its essence.             The public future submit (final callable Task) {//is packaged with a separate thread, @Async its essence.           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) {///Specific exception logic handles the place System.err.println ("Error during @Asy          NC execution: "+ ex");   }      }

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 the place where we need to focus on exception handling in the future.

Content 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 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.

Springboot asynchronous threading Simple three styles

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.