package com.yeejoin.amos.boot.module.tcm.biz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ExecuteThreadPoolConfig {

    private static final Integer CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;

    private static final Integer MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2 + 1;

    private static final Integer TASK_QUEUE_CAPACITY = Runtime.getRuntime().availableProcessors();

    private static final Integer TASK_KEEP_ALIVE_TIME = 60 * 3;

    @Bean(name = "tcmTaskExecutor")
    public ThreadPoolTaskExecutor executeThreadPoolConfig() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(TASK_QUEUE_CAPACITY);
        executor.setThreadNamePrefix("tcmTaskExecutor-");
        // 设置线程保持活跃的时间（默认：60 * 3）
        executor.setKeepAliveSeconds(TASK_KEEP_ALIVE_TIME);
        // 设置任务拒绝策略  通过主线程知行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
