package com.alibaba.csp.sentinel.dashboard.util.pool;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author by zhaowenyuan create 2022/7/26 09:28
 * 线程池
 */
public enum PoolUtils {
    /**
     * 线程池
     */
    SENTINEL("SENTINEL-POOL-SERVICE"),
    ;
    private final ThreadPoolExecutor instance;

    PoolUtils(String threadName){
        this.instance = new ThreadPoolExecutor(
                4,
                5,
                10L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(65535),
                new NameThreadFactory(threadName));
    }

    public ThreadPoolExecutor getInstance(){
        return instance;
    }

    public void destroy(){
        this.instance.shutdown();
    }

    static class NameThreadFactory implements ThreadFactory{
        private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
        private final ThreadGroup group;

        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        NameThreadFactory(String name){
            SecurityManager securityManager = System.getSecurityManager();
            group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
            if (null == name || name.isEmpty()){
                name = "pool";
            }
            namePrefix = name + "-" + POOL_NUMBER.getAndIncrement() + "-thread-";
        }

        @Override
        public Thread newThread(Runnable runnable) {
            Thread t = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement(), 0);
            if (t.isDaemon()){
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY){
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    }
}
