package com.njcn.gather.steady.checksquare.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 数据校验后台任务线程池配置。
 */
@Slf4j
@Configuration
public class SteadyChecksquareExecutorConfig {

    @Bean(name = "steadyChecksquareExecutorService", destroyMethod = "shutdown")
    public ExecutorService steadyChecksquareExecutorService() {
        AtomicInteger threadIndex = new AtomicInteger(1);
        return new ThreadPoolExecutor(
                1,
                1,
                30,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(8),
                runnable -> {
                    Thread thread = new Thread(runnable);
                    thread.setName("steady-checksquare-task-" + threadIndex.getAndIncrement());
                    return thread;
                },
                (runnable, executor) -> {
                    log.warn("数据校验任务线程池已满，拒绝新的校验任务");
                    throw new RejectedExecutionException("数据校验任务线程池已满");
                }
        );
    }
}
