This is the 8th day of my participation in the August Text Challenge. Here is a brief introduction to the concept of synchronous and asynchronous:

Synchronization: The synchronization is performed in sequence

Asynchronous: Simultaneous execution

In Java programs, most of the code is basically executed synchronously, and if the program uses asynchronous execution, the execution efficiency can be greatly improved. Typically, we use multithreading, middleware, and @async to execute programs asynchronously.

@Async

After spring 3.x, @async is built in. Let’s see how to use @async

  • Create asynchronous configuration classes

@enableasync EnableAsync support for configuring thread pools. You can specify multiple thread pools using @async (” thread pool name “)

import java.util.concurrent.ThreadPoolExecutor;

/ * * *@author CTW
 */
@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean
    public TaskExecutor taskExecutor(a) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // Set the number of core threads
        executor.setCorePoolSize(5);
        // Set the maximum number of threads
        executor.setMaxPoolSize(10);
        // Set the queue capacity
        executor.setQueueCapacity(20);
        // Set thread active time (seconds)
        executor.setKeepAliveSeconds(60);
        // Set the default thread name
        executor.setThreadNamePrefix("Test-Async");
        // Set the rejection policy
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // Wait for all tasks to complete before closing the thread pool
        executor.setWaitForTasksToCompleteOnShutdown(true);
        returnexecutor; }}Copy the code
  • Use of @async annotations

There are two cases: 1. Method does not return, 2. Method does return

@async can be written to an interface or an implementation class

  1. There is no return
@Async
public void testAsync1(a) {
    long startTime = System.currentTimeMillis();
    try {
        // The simulation takes time
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    System.out.println(Thread.currentThread().getName() + ": void testAsync1() + (endTime - startTime));
}
Copy the code
  1. Returns a
@Override
@Async
public Future<String> testAsync4(a) {
    long startTime = System.currentTimeMillis();
    try {
        // The simulation takes time
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    return new AsyncResult<>("TestAsync4: Time:" + (endTime - startTime));
}
Copy the code
  • Create interface to test (no return/call with return method and writing)

No return from call

@GetMapping("testAsync")
public String testAsync(a) {
    asyncService.testAsync1();
    return "TestAsync -- Request successful!";
}
Copy the code

You can see how long it takes to call the no-return method printCall returns

@GetMapping("testAsync2")
public String testAsync2(a) throws ExecutionException, InterruptedException {
    Future<String> stringFuture = asyncService.testAsync4();
    return "TestAsync -- Request successful!" + stringFuture.get();
}
Copy the code

You can see that the call has a return method return time

  • Execute multiple methods asynchronously

Service

@Override
@Async
public Future<String> testAsync4(a) {
    long startTime = System.currentTimeMillis();
    try {
        // The simulation takes time
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    return new AsyncResult<>("TestAsync4: Time:" + (endTime - startTime));
}

@Override
@Async
public Future<String> testAsync5(a) {
    long startTime = System.currentTimeMillis();
    try {
        // The simulation takes time
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    return new AsyncResult<>("TestAsync5: Time:" + (endTime - startTime));
}

@Override
@Async
public Future<String> testAsync6(a) {
    long startTime = System.currentTimeMillis();
    try {
        // The simulation takes time
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    return new AsyncResult<>("TestAsync6: Time:" + (endTime - startTime));
}
Copy the code

Controller

@GetMapping("testAsync4")
public String testAsync4(a) throws ExecutionException, InterruptedException {
    long startTime = System.currentTimeMillis();

    Future<String> stringFuture = asyncService.testAsync4();
    Future<String> stringFuture1 = asyncService.testAsync5();
    Future<String> stringFuture2 = asyncService.testAsync6();

    System.out.println(stringFuture.get());
    System.out.println(stringFuture1.get());
    System.out.println(stringFuture2.get());

    long endTime = System.currentTimeMillis();
    System.out.println("Request successful! Total time:" + (endTime - startTime));
    return "Request successful! Total time:" + (endTime - startTime);
}
Copy the code

You can see that the invoked method is executed synchronously

  • If operating on the main thread returns a value object, the main thread will wait, again in sequence
@GetMapping("testAsync4")
    public String testAsync4(a) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();

        Future<String> stringFuture = asyncService.testAsync4();
        System.out.println(stringFuture.get());

        Future<String> stringFuture1 = asyncService.testAsync5();
        Future<String> stringFuture2 = asyncService.testAsync6();

        System.out.println(stringFuture1.get());
        System.out.println(stringFuture2.get());

        long endTime = System.currentTimeMillis();
        System.out.println("Request successful! Total time:" + (endTime - startTime));
        return "Request successful! Total time:" + (endTime - startTime);
    }
Copy the code

TestAsync4 (), testAsync5(), testAsync6()

You must be careful to call the method before returning the object, so that the method is not executed synchronously.

How does the Controller layer asynchronously call the Service layer? How does the Service asynchronously call the Dao layer