package com.yonge.toolset.base.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Created by Eric.Shang on 23/11/16.
 */
public final class ThreadPool {
    private static ExecutorService executor;

    private ThreadPool(){}

    /**
     * 线程对象
     * @return ExecutorService
     */
    public static ExecutorService getExecutor() {
        if (executor == null) {
            synchronized (ThreadPool.class) {
                if (executor == null) {
                    executor = Executors.newFixedThreadPool(100);
                }
            }
        }
        return executor;
    }

    /**
     * 终断超时任务
     * @param executor ExecutorService
     * @param future Future
     * @param timeout 超时时间
     * @param unit 超时单位
     */
    public static Object shutdownTimeoutSubmit(ExecutorService executor, Future<?> future,
                                             Integer timeout, TimeUnit unit) {
        Object o = null;
        // 设置超时时间
        try {
            o = future.get(timeout, unit);
        } catch (Exception e) {
            future.cancel(true);
        } finally {
            executor.shutdown();
        }
        return o;
    }

}
