ThreadPoolExecutor学习笔记

背景

在开发使用spring boot 时,直接注入TaskExecutor就可以使用了,然后想知道spring boot是哪里自动注入了。

  1. 首先在网上的资料看资料,知道spring默认使用的是ThreadPoolTaskExecutor,于是去看源码,如下:
public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport
        implements AsyncListenableTaskExecutor, SchedulingTaskExecutor 
  1. 因为我不知道是在哪里初始化的,所以在ThreadPoolTaskExecutor和ExecutorConfigurationSupport各处set的方法中打了断点。


    image.png

    可以看到是在TaskExecutionAutoConfiguration初始化的。

    @Bean
    @ConditionalOnMissingBean
    public TaskExecutorBuilder taskExecutorBuilder() {
        TaskExecutionProperties.Pool pool = this.properties.getPool();
        TaskExecutorBuilder builder = new TaskExecutorBuilder();
        builder = builder.queueCapacity(pool.getQueueCapacity());
        builder = builder.corePoolSize(pool.getCoreSize());
        builder = builder.maxPoolSize(pool.getMaxSize());
        builder = builder.allowCoreThreadTimeOut(pool.isAllowCoreThreadTimeout());
        builder = builder.keepAlive(pool.getKeepAlive());
        builder = builder.threadNamePrefix(this.properties.getThreadNamePrefix());
        builder = builder.customizers(this.taskExecutorCustomizers);
        builder = builder.taskDecorator(this.taskDecorator.getIfUnique());
        return builder;
    }

    @Lazy
    @Bean(name = { APPLICATION_TASK_EXECUTOR_BEAN_NAME,
            AsyncAnnotationBeanPostProcessor.DEFAULT_TASK_EXECUTOR_BEAN_NAME })
    @ConditionalOnMissingBean(Executor.class)
    public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) {
        return builder.build();
    }
  1. 看到这里有点好奇corePoolSize和maxPoolSize的区别,因为在ThreadPoolTaskExecutor中maxPoolSize是Integer最大值。以为我没有设置,那就会使用Integer最大值,这样的线程池还有什么意义呢?

  2. 于是找到了官方说法

Core and maximum pool sizes
A ThreadPoolExecutor will automatically adjust the pool size (see getPoolSize()) according to the bounds set by corePoolSize (see getCorePoolSize()) and maximumPoolSize (see getMaximumPoolSize()). When a new task is submitted in method execute(java.lang.Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full. By setting corePoolSize and maximumPoolSize the same, you create a fixed-size thread pool. By setting maximumPoolSize to an essentially unbounded value such as Integer.MAX_VALUE, you allow the pool to accommodate an arbitrary number of concurrent tasks. Most typically, core and maximum pool sizes are set only upon construction, but they may also be changed dynamically using setCorePoolSize(int) and setMaximumPoolSize(int).

大概意思是说当一个新的任务提交时,如果当前线程小于corePoolSize那么就会新创建一个线程来处理请求,不管工作线程是否是空闲。当线程数量大于corePoolSize并且小于maxPoolSize时,则只有队列满的时候才会创建新线程。如果把corePoolSize和maxPoolSize设置为同样大小,那么就是一个固定大小的线程池。通过把maxPoolSize设置为Integer最大值,基本就允许任意数量任务。

你可能感兴趣的:(ThreadPoolExecutor学习笔记)