package com.zcloud.util;

import java.util.concurrent.*;

/**
 * 说明：TODO
 * 作者：wangxuan
 * 官网：www.zcloudchina.com
 */

public class ThreadPoolUtils {
    static int corePoolSize = Runtime.getRuntime().availableProcessors();
    static int maxPoolSize = corePoolSize * 2;
    static ExecutorService threadPool = createFixedThreadPool(corePoolSize, maxPoolSize, 1000);


    public static ExecutorService getThreadPoolService() {
        if (threadPool != null) {
            return threadPool;
        } else {
            threadPool = createFixedThreadPool(corePoolSize, maxPoolSize, 1000);
        }
        return threadPool;
    }

    public static ExecutorService createFixedThreadPool(int corePoolSize, int maxPoolSize,
                                                        int queueCapacity, ThreadFactory threadFactory,
                                                        RejectedExecutionHandler rejectionPolicy) {
        return new ThreadPoolExecutor(corePoolSize, maxPoolSize,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(queueCapacity),
                threadFactory,
                rejectionPolicy);
    }

    /**
     * 创建固定大小的线程池，默认使用 AbortPolicy 拒绝策略
     *
     * @param corePoolSize  核心线程数
     * @param maxPoolSize   最大线程数
     * @param queueCapacity 队列容量
     * @return 固定大小的线程池
     */
    public static ExecutorService createFixedThreadPool(int corePoolSize, int maxPoolSize, int queueCapacity) {
        return createFixedThreadPool(corePoolSize, maxPoolSize, queueCapacity,
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
    }

    /**
     * 创建单线程的线程池
     *
     * @param threadFactory 线程工厂
     * @return 单线程的线程池
     */
    public static ExecutorService createSingleThreadExecutor(ThreadFactory threadFactory) {
        return Executors.newSingleThreadExecutor(threadFactory);
    }

    /**
     * 创建单线程的线程池，默认使用 AbortPolicy 拒绝策略
     *
     * @return 单线程的线程池
     */
    public static ExecutorService createSingleThreadExecutor() {
        return createSingleThreadExecutor(Executors.defaultThreadFactory());
    }

    /**
     * 创建缓存型线程池
     *
     * @param threadFactory   线程工厂
     * @param rejectionPolicy 拒绝策略
     * @return 缓存型线程池
     */
    public static ExecutorService createCachedThreadPool(ThreadFactory threadFactory,
                                                         RejectedExecutionHandler rejectionPolicy) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<>(),
                threadFactory,
                rejectionPolicy);
    }

    /**
     * 创建缓存型线程池，默认使用 AbortPolicy 拒绝策略
     *
     * @return 缓存型线程池
     */
    public static ExecutorService createCachedThreadPool() {
        return createCachedThreadPool(Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
    }
}

