package mobvista.dmp.thread;

import org.apache.log4j.Logger;

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

public class TaskPool {
    private static final Logger log = Logger.getLogger(TaskPool.class);
    protected final ExecutorService threadPool;
    private static final TaskPool taskPool = new TaskPool();

    private TaskPool() {
        threadPool = Executors.newFixedThreadPool(20);
    }

    public static TaskPool getInstance() {
        return taskPool;
    }

    public static void shutdownAndAwaitTermination(ExecutorService pool) {
        pool.shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(60, TimeUnit.SECONDS))
                    log.debug("Pool did not terminate");
            }
        } catch (InterruptedException ie) {
            // (Re-)Cancel if current thread also interrupted
            pool.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }

    public static ExecutorService getThreadPool() {
        return getInstance().threadPool;
    }
}
