package com.mortals.xhx.common.utils;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 发送任务线程池
 *
 * @author: zxfei
 * @date: 2022/4/28 10:52
 */
@Component
public class SendTaskThreadPool {

    /**
     * 线程池
     */
    private ThreadPoolExecutor threadPool;

    private int poolSize;

    private volatile boolean isInit = false;

    private Object lock = new Object();

    @PostConstruct
    public void init() {
        int coreThreadNum = Runtime.getRuntime().availableProcessors();
        this.init(coreThreadNum * 2);
    }

    public void init(Integer threadNum) {
        if (poolSize < 0) {
            throw new IllegalArgumentException();
        }
        if (poolSize < Runtime.getRuntime().availableProcessors()) {
            poolSize = Runtime.getRuntime().availableProcessors() + 1;
        }
        if (!isInit) {
            synchronized (lock) {
                if (!isInit) {
                    threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadNum);

                    isInit = true;
                }
            }

        }
    }

    public void execute(Runnable command) {
        threadPool.execute(command);
    }

    public void setPoolSize(int poolSize) {
        threadPool.setCorePoolSize(poolSize);
        threadPool.setMaximumPoolSize(poolSize);
    }

    public void incrementPoolSize(int delta) {
        setPoolSize(threadPool.getCorePoolSize() + delta);
    }

    public synchronized void close() {
        if (threadPool != null) {
            threadPool.shutdown();
            threadPool = null;
            isInit = false;
        }
    }
}
