package cn.com.poc.common.pool;

import cn.com.yict.framemax.core.i18n.I18nMessageException;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

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

/**
 * SpeechToText 线程池
 */
public class SpeechToTextThreadPoolExecutor {

    final private static String THREAD_POOL_NAME = "SpeechToTextThreadExecutor";

    final private static int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();

    final private static int MAXIMUM_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 5;

    final private static int KEEP_ALIVE_TIME = 30;

    final private static LinkedBlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(CORE_POOL_SIZE * 2);

    final private static ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat(THREAD_POOL_NAME + "-%d").setDaemon(false).build();

    private static ThreadPoolExecutor THREAD_POOL_EXECUTOR;

    static {
        initThreadPool();
    }

    private static void initThreadPool() {
        THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, java.util.concurrent.TimeUnit.SECONDS, WORK_QUEUE, THREAD_FACTORY, new ThreadPoolExecutor.CallerRunsPolicy());
    }

    public static void addTask(Runnable task) {
        try {
            THREAD_POOL_EXECUTOR.execute(task);
        } catch (Exception e) {
            throw new I18nMessageException("exception/there.are.too.many.tasks.currently.please.try.again.later");
        }
    }

}
