/** * Operates like Executors.cachedThreadPool but with a custom thread timeout and pool name. * @return A new threadPool * @param maxThreadCount The maximum number of threads to allow in the pool. * @param threadTimeout the number of milliseconds that a thread should sit idle before shutting down. * @param poolName The name of the threadpool. */ public static ThreadPoolExecutor getShrinkingExecutor(int maxThreadCount, int threadTimeout, String poolName) { return new ThreadPoolExecutor(0, maxThreadCount, threadTimeout, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), getThreadFactory(poolName), new CallerRuns()); // Caller runs only occurs after shutdown, as queue size is unbounded. }
/** * Creates a new ScheduledExecutorService that will use daemon threads with appropriate names the threads. * @param size The number of threads in the threadpool * @param poolName The name of the pool (this will be printed in logs) * @return A new executor service. */ public static ScheduledExecutorService newScheduledThreadPool(int size, String poolName) { // Caller runs only occurs after shutdown, as queue size is unbounded. ScheduledThreadPoolExecutor result = new ScheduledThreadPoolExecutor(size, getThreadFactory(poolName), new CallerRuns()); // Do not execute any periodic tasks after shutdown. result.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); // Do not execute any delayed tasks after shutdown. result.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); // Remove tasks from the executor once they are done executing. By default, even when canceled, these tasks are // not removed; if this setting is not enabled we could end up with leaked (and obsolete) tasks. result.setRemoveOnCancelPolicy(true); return result; }