package cn.com.qmth.stmms.ms.commons.threadPool;

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(20);
            arbitratePoolTaskExecutor.setMaxPoolSize(40);
            arbitratePoolTaskExecutor.setKeepAliveSeconds(60);
            arbitratePoolTaskExecutor.setQueueCapacity(100);
            arbitratePoolTaskExecutor.setThreadNamePrefix("arbitrateThreadPool");

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