package com.qmth.themis.business.threadPool;

import com.qmth.themis.business.constant.SystemConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description: 线程池应用配置
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2019/3/21
 */
@Configuration
public class MyThreadPool extends ThreadPoolTaskExecutor {

    public MyThreadPool arbitratePoolTaskExecutor = null;

    @PostConstruct
    public void init() {
        arbitrateThreadPool();
    }

    /**
     * 仲裁线程池
     *
     * @return
     */
    @Bean
    public Executor arbitrateThreadPool() {
        if (arbitratePoolTaskExecutor == null) {
            arbitratePoolTaskExecutor = new MyThreadPool();
            arbitratePoolTaskExecutor.setCorePoolSize(SystemConstant.THREAD_POOL_CORE_POOL_SIZE);//核心线程数
            arbitratePoolTaskExecutor.setMaxPoolSize(SystemConstant.THREAD_POOL_MAX_POOL_SIZE);//最大线程数
            arbitratePoolTaskExecutor.setKeepAliveSeconds(SystemConstant.THREAD_POOL_KEEP_ALIVE_SECONDS);//线程空闲时间
            arbitratePoolTaskExecutor.setQueueCapacity(SystemConstant.THREAD_POOL_QUEUE_CAPACITY);//队列容量
            arbitratePoolTaskExecutor.setThreadNamePrefix(SystemConstant.THREAD_POOL_NAME);

            // rejection-policy：当pool已经达到max size的时候，如何处理新任务
            // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
            arbitratePoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            arbitratePoolTaskExecutor.initialize();
        }
        return arbitratePoolTaskExecutor;
    }
}
