package cn.hanghui.outapi.platform.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.common.config
 * @class ThreadPoolConfig
 * @date 2022/12/20 上午11:35
 * @description
 */
@Component
public class ThreadPoolConfig {
    /**
     * 参数初始化
     */
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    /**
     * 核心线程数量大小
     */
    private static final int corePoolSize = Math.max(8, Math.min(CPU_COUNT * 2 - 1, 8));
    /**
     * 线程池最大容纳线程数
     */
    private static final int maximumPoolSize = CPU_COUNT * 4 + 1;
    /**
     * 线程空闲后的存活时长
     */
    private static final int keepAliveTime = 30;

    /**
     * 线程队列长度
     */
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(500, true);


    /**
     * 线程的创建工厂
     */
    ThreadFactory threadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "thread #" + mCount.getAndIncrement());
        }
    };

    /**
     * 线程池任务满载后采取的任务拒绝策略
     */
    RejectedExecutionHandler rejectHandler = new ThreadPoolExecutor.DiscardOldestPolicy();


    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        /**
         * 线程池对象，创建线程
         */
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue, threadFactory, rejectHandler);
        return threadPoolExecutor;
    }
}
