package com.microservices.gateway.utils;

import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.threadPool.ThreadPoolExecutorWrap;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author OTTO
 */
public class CustomExecutorFactory {
    /**
     * 创建线程池
     * 存在并发处理的情况，设置核心线程为2，设置有界队列长度为100，最大线程数为10
     * 当超出队列已满且达到最大线程数时抛出异常
     * Ncpu=CPU数量
     * Ucpu=目标CPU的使用率，0<=Ucpu<=1
     * W/C=任务等待时间与任务计算时间的比率
     * Nthreads =Ncpu*Ucpu*(1+W/C)
     */
    public static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutorWrap(
            4
            , 10
            , 10
            , TimeUnit.SECONDS
            , new ArrayBlockingQueue<>(100)
            , Executors.defaultThreadFactory()
            , (r, executor) -> {
        throw new ServiceException("目前处理的人太多了，请稍后再试");
    }
    );
}
