java asynchronous call method

1, Using multithreading

Direct new thread

Thread t = new Thread(){
  @Override
  public void run() {
    longTimeMethod();
  }
};

Use thread pool

private ExecutorService executor = Executors.newCachedThreadPool() ;

    public void fun() throws Exception {

        executor.submit(new Runnable(){

            @override

                public void run() {

                    try {
                     //We have no way to write the business code to be executed. We can let the thread rest for a few seconds for testing

                        Thread.sleep(10000);

                        System.out.print("Enough sleep.~");

                    }catch(Exception e) {

                        throw new RuntimeException("Wrong report!!");

                    }

                }

        });

    }

2, Use Spring's asynchronous method to execute (no return value)

Add @ EnableAsync annotation to startup class or configuration class

package me.deweixu.aysncdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(AysncDemoApplication.class, args);
 }
}

First, encapsulate the longTimeMethod into the Spring asynchronous method. This method must be written in the Spring managed class. Note the annotation @ Async

@Async annotation can be used on methods, classes and classes, and it can work on all methods in a class

@Service
public class AsynchronousService{
  @Async
  public void springAsynchronousMethod(){
    longTimeMethod();
  }
}

Other classes call this method. It is important to note that other classes are not effective if they are called in the same class. For specific reasons, you can learn the principle of Spring AOP

@Autowired
private AsynchronousService asynchronousService;

public void useAsynchronousMethod(){
  //Code 1 we need to execute
  asynchronousService.springAsynchronousMethod();
 //Code 2 we need to execute
}

3, Using Spring's asynchronous method + Future to receive the return value

First, encapsulate longTimeMethod into Spring's asynchronous method. The return value of this asynchronous method is an instance of Future. This method must be written in Spring managed classes, and pay attention to annotation @ Async.

@Service
public class AsynchronousService{
  @Async
  public Future springAsynchronousMethod(){
    Integer result = longTimeMethod();
    return new AsyncResult(result);
  }
}

Other classes call this method. It is important to note that other classes are not effective if they are called in the same class.

If the return value is received after the call, it will be asynchronous operation if the return value is not operated. If the return value is operated, it will be synchronous operation. The following process of the main process will continue until the return value is operated

@Autowired
private AsynchronousService asynchronousService;

public void useAsynchronousMethod(){
    Future future = asynchronousService.springAsynchronousMethod();
    future.get(1000, TimeUnit.MILLISECONDS);
}

4, Native Future method

//Code 1 we need to execute
Future future = longTimeMethod2();
//Code 2 we need to execute
Integer result = future.get();

As you can see, we call longTimeMethod2 to return a Future object (note that longTimeMethod2 here is certainly not the longTimeMethod above), and then process "code 2 we need to execute". When we need to return the result, we can directly call future.get() to get the return value. Let's see how longTimeMethod2 is implemented.

private Future longTimeMethod2() {
  //Create thread pool
  ExecutorService threadPool = Executors.newCachedThreadPool();
  //Get asynchronous Future object
  Future future = threadPool.submit(new Callable() {
    @Override
    public Integer call() throwsException {
        return longTimeMethod();
    }
  });
  return future;
}

Reference resources

Original link: https://www.jianshu.com/p/51f0555b232a

Keywords: Java Spring REST

Added by mrwhale on Tue, 28 Jan 2020 16:01:00 +0200