Java tutorial
//package com.java2s; /* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class Main { /** * Properly shutdown and await pool termination for an arbitrary * amount of time. * * @param pool Pool to shutdown * @param waitSeconds Seconds to wait before throwing exception * @throws java.util.concurrent.TimeoutException Thrown if the pool does not shutdown in the specified time */ public static void shutdownAndWaitForTermination(ExecutorService pool, int waitSeconds) throws TimeoutException { // shut it down pool.shutdown(); try { // wait, wait, wait if (!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) { // things still running, nuke it pool.shutdownNow(); // wait, wait, wai if (!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) { // boo hiss, didn't shutdown throw new TimeoutException("Pool did not terminate"); } } } catch (InterruptedException ie) { // try, try again pool.shutdownNow(); Thread.currentThread().interrupt(); } } }