package org.tio.sitexxx.service;

import org.tio.sitexxx.service.vo.Const;
import org.tio.utils.thread.pool.DefaultThreadFactory;
import org.tio.utils.thread.pool.TioCallerRunsPolicy;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-07-01 10:08
 *    desc   : 线程池工具类
 * </pre>
 */
public class ThreadUtil {
    private static int MAX_POOL_SIZE_FOR_BS	= 256;
    private static ThreadPoolExecutor bsExecutor = null;
    private static ThreadPoolExecutor pushExecutor = null;

    /**
     * 获取业务系统的常规线程池
     * @return
     */
    public static ThreadPoolExecutor getBsExecutor() {
        if (bsExecutor != null) {
            return bsExecutor;
        }

        synchronized (Const.class) {
            if (bsExecutor != null) {
                return bsExecutor;
            }

            LinkedBlockingQueue<Runnable> runnableQueue = new LinkedBlockingQueue<>();
            String threadName = "chat-bs";
            DefaultThreadFactory threadFactory = DefaultThreadFactory.getInstance(threadName, Thread.NORM_PRIORITY);
            ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new TioCallerRunsPolicy();
            bsExecutor = new ThreadPoolExecutor(MAX_POOL_SIZE_FOR_BS, MAX_POOL_SIZE_FOR_BS, 0, TimeUnit.SECONDS, runnableQueue, threadFactory, callerRunsPolicy);
            bsExecutor.prestartCoreThread();
            return bsExecutor;
        }
    }

    /**
     * 获取业务系统的常规线程池
     * @return
     */
    public static ThreadPoolExecutor getPushExecutor() {
        if (pushExecutor != null) {
            return pushExecutor;
        }

        synchronized (Const.class) {
            if (pushExecutor != null) {
                return pushExecutor;
            }

            LinkedBlockingQueue<Runnable> runnableQueue = new LinkedBlockingQueue<>();
            String threadName = "tio-push";
            DefaultThreadFactory threadFactory = DefaultThreadFactory.getInstance(threadName, Thread.MIN_PRIORITY);
            ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new TioCallerRunsPolicy();
            pushExecutor = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS, runnableQueue, threadFactory, callerRunsPolicy);
            pushExecutor.prestartCoreThread();
            return pushExecutor;
        }
    }
}
