Easy Fork-Join with Spring

In the first two days, my brother asked me about the Fork-Join situation, and I briefly explained it. By the way, @Async in Spring will intelligently encapsulate the calling function and throw it to the thread pool. All you have to do is simply configure the thread pool.

The following is the sample code, only the code and results are given here:

In the first case, the Service class:

@Async
public String test1() {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 1 start", threadName);
    try {
        Thread.sleep(5000L);
    } catch (Exception e){
    }
    log.error("{}: 1 end", threadName);
    return "s1";
}

@Async
public String test2() {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 2 start", threadName);
    try {
        Thread.sleep(2000L);
    } catch (Exception e){
    }
    log.error("{}: 2 end", threadName);
    return "s2";
}

Controller class:

try {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 0 start", threadName);
    PrintWriter out = response.getWriter();
    String f1 = testService.test1();
    String f2 = testService.test2();
    log.error("{}: 0 end {} {}", threadName, f1, f2);

} catch (Exception e) {
}

 

The result is that test1 and test2 are executed in different threads, but the calls to test1 and test2 end immediately, and f1 and f2 are both null.

That is to say, two background tasks can be executed independently in this way, but it cannot wait for the result to be returned. How can I get the result?

 

In the second case, the Service class:

@Async
public Future<String> test1() {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 1 start", threadName);
    try {
        Thread.sleep(5000L);
    } catch (Exception e){
    }
    log.error("{}: 1 end", threadName);
    return new AsyncResult<>("s1");
}

@Async
public Future<String> test2() {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 2 start", threadName);
    try {
        Thread.sleep(2000L);
    } catch (Exception e){
    }
    log.error("{}: 2 end", threadName);
    return new AsyncResult<>("s2");
}

 

Controller class:

try {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 0 start", threadName);
    PrintWriter out = response.getWriter();
    Future<String> f1 = testService.test1();
    Future<String> f2 = testService.test2();
    
    log.error("{}: 0 end {} {}", threadName, f1.get(), f2.get());
} catch (Exception e) {
}

 

This gives the correct result. In short, Future<T> and AsyncResult<T> allow the calling thread to join and wait for the Future result.

 

 

 

 

Guess you like

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