package org.dromara.zhishu.manager;

import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;

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

@Component
public class TaskExecutorManager {

    private final ExecutorService executor;

    public TaskExecutorManager() {
        // 使用有界队列和合理的线程数
        this.executor = new ThreadPoolExecutor(
                4, // 核心线程数
                8, // 最大线程数
                60L, TimeUnit.SECONDS, // 空闲线程存活时间
                new ArrayBlockingQueue<>(20), // 有界队列，防止无限堆积
                new ThreadPoolExecutor.CallerRunsPolicy() // 重要：拒绝策略
        );
    }

    public ExecutorService getExecutor() {
        return executor;
    }

    @PreDestroy
    public void shutdown() {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
        }
    }
}