package com.yifu.cloud.plus.v1.yifu.social.concurrent.threadpool;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @description: 社保导入线程池初始化配置
 * @author: wangweiguo
 * @date: 2021/6/30
 */

public class YFSocialImportThreadPoolExecutor extends ThreadPoolExecutor {

    private static final int CORE_POOL_SIZE = 8;
    private static final int MAX_POOL_SIZE = 12;
    private static final long KEEP_ALIVE_TIME = 15;
    private static final int CAPACITY = 1024;

    /**
     * @description: 社保导入线程池构造方法
     * @param yfThreadFactory
     * @return:
     * @author: wangweiguo
     * @date: 2021/8/4
     */
    public YFSocialImportThreadPoolExecutor(YFThreadFactory yfThreadFactory) {
        super(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<>(CAPACITY), yfThreadFactory, (runnable, executor) -> {
            try {
                final Thread t = new Thread(runnable, "Temporary task executor");
                t.start();
            } catch (Throwable e) {
                throw new RejectedExecutionException(
                        "Failed to start a new thread", e);
            }
        });
    }

    /**
     * @description: 获取剩余可以添加的任务数量
     * @return: int
     * @author: wangweiguo
     * @date: 2021/8/4
     */
    public int getResidualCapacity() {
        return CAPACITY - this.getQueue().size() + this.getPoolSize() - this.getActiveCount();
    }

}
