Code example for ExecutorService

Methods: awaitTerminationshutdownshutdownNow

	 * @param pool 
	 * @param allowedTime 
	 * @throws Exception 
	public static void shutdownThreadPoolAndAwaitTermination(ExecutorService pool, int allowedTime) throws Exception {
		pool.shutdown(); // Disable new tasks from being submitted
		try { 
			// Wait a while for existing tasks to terminate 
			if (!pool.awaitTermination(allowedTime, TimeUnit.SECONDS)) {
				pool.shutdownNow(); // Cancel currently executing tasks
				// Wait a while for tasks to respond to being cancelled 
				if (!pool.awaitTermination(allowedTime, TimeUnit.SECONDS)) {
					throw new Exception("Pool did not terminate!");
		} catch (InterruptedException ie) {
			// (Re-)Cancel if current thread also interrupted 
			// Preserve interrupt status 
			throw ie;
Experience pair programming with AI  Get Codota for Java