Java tutorial
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.ld4lindexing; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Run these tasks in parallel. If the queue becomes too large, then submitted * jobs will run in the thread of the submitter. * * On a call to shutdownAndWait(), we actually wait up to 20 seconds before * calling shutdown on the thread pool. That allows running tasks to submit * other tasks, at least for a while. */ public class ThreadPool { private static final Log log = LogFactory.getLog(ThreadPool.class); private final ThreadPoolExecutor service; public ThreadPool(Settings settings) { int poolSize = settings.getThreadPoolSize(); int queueSize = settings.getTaskQueueSize(); this.service = new ThreadPoolExecutor(poolSize, poolSize, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize), new ThreadPoolExecutor.CallerRunsPolicy()); } public void submit(Runnable runnable) { service.submit(runnable); } public void shutdownAndWait() { waitForIdle(); service.shutdown(); try { service.awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException("While waiting for threadpool shutdown", e); } } private void waitForIdle() { log.info("Shutdown requested."); try { for (int i = 0; i < 20; i++) { if (service.getActiveCount() == 0) { Thread.sleep(500); if (service.getActiveCount() == 0) { return; } } Thread.sleep(500); } } catch (InterruptedException e) { log.error("Shutdown thread interrupted!"); Thread.currentThread().interrupt(); } finally { log.info("Shutdown complete."); } } }