package jnpf.attendance.service.handle.notification;

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

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

@Component
@Slf4j
public class TenantResourceManager {
    // 共享线程池 - 避免为每个小租户创建独立线程池
    private final ThreadPoolExecutor sharedThreadPool;

    public TenantResourceManager() {
        // 优化的线程池配置
        this.sharedThreadPool = new ThreadPoolExecutor(
            20,  // 核心线程数
            100, // 最大线程数
            60L, // 空闲线程存活时间
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(10000), // 队列大小
            new ThreadFactory() {
                private final AtomicInteger threadNumber = new AtomicInteger(1);
                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r, "tenant-shared-thread-" + threadNumber.getAndIncrement());
                    t.setDaemon(false);
                    return t;
                }
            },
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );
    }

    public Executor getSharedThreadPool() {
        return sharedThreadPool;
    }

    @PreDestroy
    public void shutdown() {
        sharedThreadPool.shutdown();
        try {
            if (!sharedThreadPool.awaitTermination(30, TimeUnit.SECONDS)) {
                sharedThreadPool.shutdownNow();
            }
        } catch (InterruptedException e) {
            sharedThreadPool.shutdownNow();
            Thread.currentThread().interrupt();
        }
        log.info("TenantResourceManager shutdown completed");
    }
}
