package digital.laboratory.platform.inspection.threadpool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * 定义全局线程池
 */
@Slf4j
@Component
public class GlobalThreadPool {

    // 定义全局线程池，使用单列模式
    private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(
            10, // 核心线程数
            50, // 最大线程数
            60L, TimeUnit.SECONDS, // 空闲线程存活时间
            new LinkedBlockingQueue<Runnable>(100), // 任务队列
            Executors.defaultThreadFactory(), // 线程工厂
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
    );

    // 私有化构造方法，防止外部实例化
    private GlobalThreadPool() {}

    // 获取全局线程池实列
    public static ExecutorService getInstance() {
        return THREAD_POOL;
    }

    // 关闭线程池
    public static void shutdown() {
        THREAD_POOL.shutdown();
    }

    // 在应用关闭前执行
    @PreDestroy
    public void destroy() {
        log.info("Spring 应用关闭，正在关闭线程池...");
        shutdown();
        try {
            if (!THREAD_POOL.awaitTermination(60, TimeUnit.SECONDS)) {
                THREAD_POOL.shutdownNow();
            }
        } catch (InterruptedException e) {
            THREAD_POOL.shutdownNow();
        }
    }
}
