关于@Async注解所起子线程会随着主线程退出而退出的问题的分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daijiguo/article/details/85078433

一、@Async代码示例:

AbstractTask.java

public abstract class AbstractTask {
    private static Random random = new Random();

    public void doTaskOne() throws Exception {
        System.out.println("开始做任务一,线程名:"+ Thread.currentThread().getName());
        long start = currentTimeMillis();
        sleep(random.nextInt(10000));
        Test2.query();

        long end = currentTimeMillis();
        System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
    }

    public void doTaskTwo() throws Exception {
        System.out.println("开始做任务二,线程名:"+ Thread.currentThread().getName());
        long start = currentTimeMillis();
        sleep(random.nextInt(10000));
        long end = currentTimeMillis();
        System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
    }

    public void doTaskThree() throws Exception {
        System.out.println("开始做任务三,线程名:"+ Thread.currentThread().getName());
        long start = currentTimeMillis();
        sleep(random.nextInt(10000));
        long end = currentTimeMillis();
        System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
    }
}

AsyncTask.java

@Service
public class AsyncTask<Component> extends AbstractTask {
    @Async("taskExecutor")
    public void doTaskOne() throws Exception {
        super.doTaskOne();
    }

    @Async("taskExecutor")
    public void doTaskTwo() throws Exception {
        super.doTaskTwo();
    }

    @Async("taskExecutor")
    public void doTaskThree() throws Exception {
        super.doTaskThree();
    }
}

AsyncTaskTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncTaskTest {
    @Autowired
    private AsyncTask task;

    @Test
    public void testAsyncTasks() throws Exception {
		long start = currentTimeMillis();
		task.doTaskOne();
		task.doTaskTwo();
		task.doTaskThree();
		long end = currentTimeMillis();
		System.out.println("总共耗时:" + (end - start) + "毫秒");
    }
}

二、现象:

示例输出:

总共耗时:6毫秒
开始做任务三,线程名:pool-1-thread-3
开始做任务二,线程名:pool-1-thread-2
开始做任务一,线程名:pool-1-thread-1

可见,线程1、线程2、线程3并没有真正执行完,就随着主线程全都结束了。


三、现象分析:

@Async本应该跟起子线程执行任务一个道理,为何子线程会随着主线程的结束而结束?难道通过正常手段起的子线程,也是如此?因此做了以下实验:

class MyThread extends Thread {
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(111111);
    }
}
public class Test3{
    public static void main(String[] args) {
        MyThread th = new MyThread();
        th.start();
        System.out.println(222222);
    }
}

输出结果:

222222
111111

关键词:setdeamon

可见,主线程结束后,子线程任然完成了计算任务再退出。所以,@Async下的子线程为什么会随着主线程的退出而退出呢,是因为@Async中有类似setdaemon(true)的代码存在吗?参考:《java主线程结束和子线程结束之间的关系》


关键词:SimpleAsyncTaskExecutor

在@Async源码中找了一圈,发现了这样一句话:

By default, Spring will be searching for an associated thread pool definition: either a unique TaskExecutor bean in the context, or an Executor bean named “taskExecutor” otherwise. If neither of the two is resolvable, a SimpleAsyncTaskExecutor will be used to process async method invocations.
意即,默认情况下spring会先搜索TaskExecutor类型的bean或者名字为taskExecutor的Executor类型的bean作为执行器,都不存在使用SimpleAsyncTaskExecutor执行器。参考:《异步任务spring @Async注解源码解析》


再次搜索SimpleAsyncTaskExecutor相关资料,发现,SimpleAsyncTaskExecutor所起子线程,是不会跟随主线程的退出而退出的。参考:Stack Overflow,文中建议使用ThreadPoolTaskExecutor来控制主线程和子线程的退出关系。
那么,问题既然不是出在@Async注解上,会是什么原因导致子线程随主线程退出的呢?


四、谜底揭晓:

偶然碰到这篇文章参考:《由@Async使用引发的思考,实现优雅关闭线程》,发现原因竟然出在@SpringBootTest注解上。于是,做了如下实验,将常规手段所起的子线程,放入单元测试中去跑,看子线程是否还会在主线程退出之后,继续执行?

class MyThread2 extends Thread {
    public void run() {
        try {
            Thread.sleep(5000);
            Test2.query();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(111111);
    }
}

@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncTaskTest {
    @Autowired
    private AsyncTask task;

    @Test
    public void testAsyncTasks() throws Exception {
        MyThread2 th = new MyThread2();
        th.start();
        System.out.println(222222);
    }
}

执行结果:

222222

果然,子线程提前结束了。看来真的是单元测试在作祟。


五、结论:

如果是非springboot项目,我们不会将代码写在单元测试中,子线程不会提前结束,即非守护线程,不会随着主线程的退出而退出。

如果是springboot项目,即使存在类似@SpringBootTest的回收bean的情况,由于webapp不会轻易退出,即主线程不会轻易退出,因此也不必担心子线程提前退出的情况。

但是《由@Async使用引发的思考,实现优雅关闭线程》中也考虑到一种极端情况,就是在很多子线程正在完成大量任务的时候,人为关闭了springboot进程,则子线程还是会随着主线程退出而退出,导致任务强制结束而产生系统错误。因此建议自己定义执行器ThreadPoolTaskExecutor,通过它的setWaitForTasksToCompleteOnShutdown()函数来强制子线程完成任务!

参考:
https://www.cnblogs.com/dennyzhangdd/p/9026303.html#_label1_0
https://www.logicbig.com/tutorials/spring-framework/spring-core/async-annotation.html
https://juejin.im/post/5b27b8366fb9a00e46675879
https://my.oschina.net/kipeng/blog/1795537
https://stackoverflow.com/questions/2236966/shutting-down-a-taskexecutor-in-a-web-application-when-the-web-server-is-shutdow
https://www.cnblogs.com/qiumingcheng/p/8202393.html

猜你喜欢

转载自blog.csdn.net/daijiguo/article/details/85078433