package org.jeecg.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

@Configuration
public class BizThreadPoolConfig {

    private final int POOL_SIZE = Runtime.getRuntime().availableProcessors();
    private final long KEEP_ALIVE_TIME = 0L;

    @Bean("asyncThreadPool")
    public ExecutorService asyncExecutors() {
        return new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new CustomThreadFactory("AsyncThreadPool"));
    }

    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);
        }
    }
}

