001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.utils.concurrent;
015
016import java.util.concurrent.ExecutorService;
017import java.util.concurrent.TimeUnit;
018
019import org.slf4j.Logger;
020import org.slf4j.LoggerFactory;
021
022/**
023 *
024 */
025public class ExecutorUtils {
026  private static final Logger LOG = LoggerFactory.getLogger(ExecutorUtils.class);
027
028  /**
029   * Shuts down an executor and waits up to 1 hour for the already submitted jobs to finish.
030   * @param exec
031   */
032  public static void stop(ExecutorService exec) {
033    stop(exec, 1, TimeUnit.HOURS);
034  }
035
036  /**
037   * Shuts down an executor and waits for the job to finish until the given timeout is reached
038   * before forcing an immediate shutdown.
039   * @param exec
040   * @param timeout
041   * @param unit
042   */
043  public static void stop(ExecutorService exec, int timeout, TimeUnit unit) {
044    LOG.debug("Shutting down executor service {}", exec);
045    exec.shutdown(); // Disable new tasks from being submitted
046    try {
047      if (!exec.awaitTermination(timeout, unit)) {
048        LOG.warn("Forcing shut down of executor service, pending tasks will be lost! {}", exec);
049        exec.shutdownNow();
050      }
051    } catch (InterruptedException ie) {
052      LOG.warn("Forcing shut down of executor service, pending tasks will be lost! {}", exec);
053      exec.shutdownNow();
054      // Preserve interrupt status
055      Thread.currentThread().interrupt();
056    }
057  }
058}