ThreadPoolExecutor的的核心线程回收设置allowCoreThreadTimeOut

如果你对ThreadPoolExecutor的执行还不了解,可以参考有界、无界队列对ThreadPoolExcutor执行的影响这篇文章。

在ThreadPoolExecutor类中有个allowCoreThreadTimeOut(boolean value)方法,该方法用来设置是否回收在保活时间后依然没没有任务执行核心线程。

下面通过程序来验证该参数的设置,如果你对CountDownLatch不了解,可以参考并发工具类:等待多线程完成的CountDownLatch,和join的区别

public class PoolThreadRecycling {

    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final int QUEUE_CAPACITY = 1;
    private static final Long KEEP_ALIVE_TIME = 1L;

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(QUEUE_CAPACITY),
            new ThreadPoolExecutor.CallerRunsPolicy());
    static {
        //如果设置为true,当任务执行完后,所有的线程在指定的空闲时间后,poolSize会为0
        //如果不设置,或者设置为false,那么,poolSize会保留为核心线程的数量
        executor.allowCoreThreadTimeOut(true);
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 1; i <= 10; i++) {
            executor.submit(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }

            });
        }

        System.out.println("poolSize:" + executor.getPoolSize());
        System.out.println("core:" + executor.getCorePoolSize());
        System.out.println("活跃:" + executor.getActiveCount());

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("开始检测线程池中线程数量");
        while (true) {
            Thread.sleep(1000);

            System.out.println("poolSize:" + executor.getPoolSize());
            System.out.println("core:" + executor.getCorePoolSize());
            System.out.println("活跃:" + executor.getActiveCount());
            System.out.println("======");

        }

    }
}

代码中的静态代码块中通过executor.allowCoreThreadTimeOut(true);设置回收核心线程,执行结果如下:

poolSize:9
core:5
活跃:9
开始检测线程池中线程数量
poolSize:1
core:5
活跃:0
======
poolSize:0
core:5
活跃:0
======
poolSize:0
core:5
活跃:0
======

可以看到,当设置为ture时,线程池中的任务都执行完后,线程池中的线程数量是0,因为核心线程也都被回收了。

如果将其设置为false呢,执行结果如下

poolSize:9
core:5
活跃:9
开始检测线程池中线程数量
poolSize:5
core:5
活跃:0
======
poolSize:5
core:5
活跃:0
======

线程池中的任务都执行完后,线程池中核心线程没有被回收。

该属性缺省值为false

这个参数设置成true还是false需要根据你具体的业务判断,如果该业务需要执行的次数并不多,采用多线程只是为了缩短执行的时间,那么可以设置成true,毕竟用完后很长时间才会用到,线程干耗着也是耗费资源的。但是如果是需要较高并发执行的业务,那么可以设置为false,保留着线程,避免每次都得创建线程耗费资源。


版权声明:本文为kusedexingfu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。