package org.jeecg.common.util;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池工具类
 *
 * @author sunweidong
 * @since 2024/6/4
 */
public class ScheduledThreadPoolUtil {

    /**
     * 核心线程数
     */
    private static final int CORE_SIZE = 2;
    /**
     * 工厂名
     */
    private static final String THREAD_FACTORY_NAME = "SERVICE-SCHEDULED-THREAD-POOL";

    /**
     * 私有化构造
     */
    private ScheduledThreadPoolUtil() {
    }

    private static class Inner {
        private static final ScheduledThreadPoolExecutor THREAD_POOL_EXECUTOR =
                new ScheduledThreadPoolExecutor(CORE_SIZE, defaultThreadFactory(), defaultRejectHandler());
    }

    public static ScheduledThreadPoolExecutor getInstance() {
        return Inner.THREAD_POOL_EXECUTOR;
    }

    private static CustomThreadFactory defaultThreadFactory() {
        return new CustomThreadFactory(THREAD_FACTORY_NAME);
    }

    private static CustomRejectHandler defaultRejectHandler() {
        return new CustomRejectHandler();
    }

    static class CustomThreadFactory implements ThreadFactory {
        private final String PREFIX_NAME;
        private final AtomicInteger id = new AtomicInteger(1);

        CustomThreadFactory(String featureOfFactory) {
            PREFIX_NAME = "CustomThreadFactory: " + featureOfFactory + "-";
        }

        @Override
        public Thread newThread(Runnable target) {
            String name = PREFIX_NAME + id.getAndIncrement();
            return new Thread(Thread.currentThread().getThreadGroup(), target, name, 0);
        }
    }

    static class CustomRejectHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
            throw new RejectedExecutionException("Task " + task.toString()
                    + " rejected from " + executor.toString());
        }
    }

}
