package com.mortals.xhx.common.utils;

import org.springframework.stereotype.Component;

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


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