程序员子龙(Java面试 + Java学习) 程序员子龙(Java面试 + Java学习)
首页
学习指南
工具
开源项目
技术书籍

程序员子龙

Java 开发从业者
首页
学习指南
工具
开源项目
技术书籍
  • 基础

  • JVM

  • Spring

  • 并发编程

  • Mybatis

  • 网络编程

  • 数据库

  • 缓存

  • 设计模式

  • 分布式

  • 高并发

  • SpringBoot

    • SpringBoot 整合redis
    • SpringBoot 线程池
      • springboot下整合mybatis
      • spring boot 配置文件的加载顺序
      • springboot启动不加载bootstrap.yml文件的问题解决
      • SpringBoot设置动态定时任务
      • springboot整合hibernate
      • ApplicationRunner、InitializingBean、@PostConstruct使用详解
      • Spring Boot 优雅的参数校验方案
      • ELK处理 SpringBoot 日志,太优雅了!
      • SpringBoot配置数据源
      • Spring Boot 默认数据库连接池 —— HikariCP
      • 数据库连接池Hikari监控
      • Spring Boot中使用AOP统一处理Web请求日志
      • SpringBoot 三大开发工具,你都用过么?
      • Spring Boot 3.2 + CRaC = 王炸!
      • springboot启动的时候排除加载某些bean
      • spring boot中集成swagger
      • springboot项目引入这个包以后把原来的json报文改为了xml格式返回
      • SpringBoot中new对象不能自动注入对象和属性的问题
      • 使用 Spring Boot Actuator 监控应用
      • 记录一次springboot自动任务线上突然不执行问题排查过程
      • SpringBoot定时任务@Scheduled源码解析
      • Spring Boot + Lua = 王炸!
      • Spring Boot 实现定时任务动态管理
      • SpringBoot的@Async注解有什么坑?
      • druid 参数配置详解
      • Spring Boot HandlerMethodArgumentResolver 使用和场景
      • SpringBoot数据加解密
      • 解决controller层注入的service为null
      • 在 Spring Boot 中通过 RequestBodyAdvice 统一解码请求体
      • SpringBoot之使用Redisson实现分布式锁(含完整例子)
    • SpringCloudAlibaba

    • Nginx

    • 面试

    • 生产问题

    • 系统设计

    • 消息中间件

    • Java
    • SpringBoot
    程序员子龙
    2024-01-29
    目录

    SpringBoot 线程池

    # springboot 默认线程池

    自动配置类EnableAutoConfiguration 为 key 的所有类:该配置文件在 spring-boot-autoconfigure jar 包中spring.factories文件里。

    org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,
    
    1
    @ConditionalOnClass(ThreadPoolTaskExecutor.class)
    @Configuration(proxyBeanMethods = false)
    @EnableConfigurationProperties(TaskExecutionProperties.class)
    public class TaskExecutionAutoConfiguration {
    
       /**
        * Bean name of the application {@link TaskExecutor}.
        */
       public static final String APPLICATION_TASK_EXECUTOR_BEAN_NAME = "applicationTaskExecutor";
    
       @Bean
       @ConditionalOnMissingBean
       public TaskExecutorBuilder taskExecutorBuilder(TaskExecutionProperties properties,
             ObjectProvider<TaskExecutorCustomizer> taskExecutorCustomizers,
             ObjectProvider<TaskDecorator> taskDecorator) {
          TaskExecutionProperties.Pool pool = 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());
          Shutdown shutdown = properties.getShutdown();
          builder = builder.awaitTermination(shutdown.isAwaitTermination());
          builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod());
          builder = builder.threadNamePrefix(properties.getThreadNamePrefix());
          builder = builder.customizers(taskExecutorCustomizers.orderedStream()::iterator);
          builder = builder.taskDecorator(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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40

    默认的线程池配置在org.springframework.boot.autoconfigure.task.TaskExecutionProperties文件

    @ConfigurationProperties("spring.task.execution")
    public class TaskExecutionProperties {
    
       private final Pool pool = new Pool();
    
       private final Shutdown shutdown = new Shutdown();
    
       /**
        * Prefix to use for the names of newly created threads.
        */
       private String threadNamePrefix = "task-";
    
       public Pool getPool() {
          return this.pool;
       }
    
       public Shutdown getShutdown() {
          return this.shutdown;
       }
    
       public String getThreadNamePrefix() {
          return this.threadNamePrefix;
       }
    
       public void setThreadNamePrefix(String threadNamePrefix) {
          this.threadNamePrefix = threadNamePrefix;
       }
    
       public static class Pool {
    
          /**
           * Queue capacity. An unbounded capacity does not increase the pool and therefore
           * ignores the "max-size" property.
           */
          private int queueCapacity = Integer.MAX_VALUE;
    
          /**
           * Core number of threads.
           */
          private int coreSize = 8;
    
          /**
           * Maximum allowed number of threads. If tasks are filling up the queue, the pool
           * can expand up to that size to accommodate the load. Ignored if the queue is
           * unbounded.
           */
          private int maxSize = Integer.MAX_VALUE;
    
          /**
           * Whether core threads are allowed to time out. This enables dynamic growing and
           * shrinking of the pool.
           */
          private boolean allowCoreThreadTimeout = true;
    
          /**
           * Time limit for which threads may remain idle before being terminated.
           */
          private Duration keepAlive = Duration.ofSeconds(60);
    
          public int getQueueCapacity() {
             return this.queueCapacity;
          }
    
          public void setQueueCapacity(int queueCapacity) {
             this.queueCapacity = queueCapacity;
          }
    
          public int getCoreSize() {
             return this.coreSize;
          }
    
          public void setCoreSize(int coreSize) {
             this.coreSize = coreSize;
          }
    
          public int getMaxSize() {
             return this.maxSize;
          }
    
          public void setMaxSize(int maxSize) {
             this.maxSize = maxSize;
          }
    
          public boolean isAllowCoreThreadTimeout() {
             return this.allowCoreThreadTimeout;
          }
    
          public void setAllowCoreThreadTimeout(boolean allowCoreThreadTimeout) {
             this.allowCoreThreadTimeout = allowCoreThreadTimeout;
          }
    
          public Duration getKeepAlive() {
             return this.keepAlive;
          }
    
          public void setKeepAlive(Duration keepAlive) {
             this.keepAlive = keepAlive;
          }
    
       }
    
       public static class Shutdown {
    
          /**
           * Whether the executor should wait for scheduled tasks to complete on shutdown.
           */
          private boolean awaitTermination;
    
          /**
           * Maximum time the executor should wait for remaining tasks to complete.
           */
          private Duration awaitTerminationPeriod;
    
          public boolean isAwaitTermination() {
             return this.awaitTermination;
          }
    
          public void setAwaitTermination(boolean awaitTermination) {
             this.awaitTermination = awaitTermination;
          }
    
          public Duration getAwaitTerminationPeriod() {
             return this.awaitTerminationPeriod;
          }
    
          public void setAwaitTerminationPeriod(Duration awaitTerminationPeriod) {
             this.awaitTerminationPeriod = awaitTerminationPeriod;
          }
    
       }
    
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132

    可以在配置文件中指定参数值,例如:

    spring.task.execution.threadNamePrefix=sportsThread
    spring.task.execution.pool.coreSize=20
    
    1
    2

    调用示例:

    @Autowired
    private Executor executorService;
    
    public void test(){
        executorService.execute( () ->{
        // todo 业务代码
    
        });
    
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    # 使用自定义线程池

    @Configuration
    public class ThreadPoolConfig {
        @Bean("myExecutor")
        public Executor taskExecutor() {
            ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
            //设置线程池参数信息
            taskExecutor.setCorePoolSize(10);
            taskExecutor.setMaxPoolSize(50);
            taskExecutor.setQueueCapacity(200);
            taskExecutor.setKeepAliveSeconds(60);
            taskExecutor.setThreadNamePrefix("myExecutor--");
            taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
            taskExecutor.setAwaitTerminationSeconds(60);
            //修改拒绝策略为使用当前线程执行
            taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            //初始化线程池
            taskExecutor.initialize();
            return taskExecutor;
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    调用示例:

    @Autowired
    private Executor myExecutor;
    
    public void test(){
        myExecutor.execute( () ->{
        // todo 业务代码
    
        });
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    上次更新: 2024/01/30, 15:08:57
    SpringBoot 整合redis
    springboot下整合mybatis

    ← SpringBoot 整合redis springboot下整合mybatis→

    最近更新
    01
    一个注解,优雅的实现接口幂等性
    11-17
    02
    MySQL事务(超详细!!!)
    10-14
    03
    阿里二面:Kafka中如何保证消息的顺序性?这周被问到两次了
    10-09
    更多文章>
    Theme by Vdoing | Copyright © 2024-2024

        辽ICP备2023001503号-2

    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式