001package org.gbif.utils.concurrent;
002
003import java.util.concurrent.ExecutorService;
004import java.util.concurrent.TimeUnit;
005
006import org.slf4j.Logger;
007import org.slf4j.LoggerFactory;
008
009/**
010 *
011 */
012public class ExecutorUtils {
013  private static final Logger LOG = LoggerFactory.getLogger(ExecutorUtils.class);
014
015  /**
016   * Shuts down an executor and waits up to 1 hour for the already submitted jobs to finish.
017   * @param exec
018   */
019  public static void stop(ExecutorService exec) {
020    stop(exec, 1, TimeUnit.HOURS);
021  }
022
023  /**
024   * Shuts down an executor and waits for the job to finish until the given timeout is reached
025   * before forcing an immediate shutdown.
026   * @param exec
027   * @param timeout
028   * @param unit
029   */
030  public static void stop(ExecutorService exec, int timeout, TimeUnit unit) {
031    LOG.debug("Shutting down executor service {}", exec);
032    exec.shutdown(); // Disable new tasks from being submitted
033    try {
034      if (!exec.awaitTermination(timeout, unit)) {
035        LOG.warn("Forcing shut down of executor service, pending tasks will be lost! {}", exec);
036        exec.shutdownNow();
037      }
038    } catch (InterruptedException ie) {
039      LOG.warn("Forcing shut down of executor service, pending tasks will be lost! {}", exec);
040      exec.shutdownNow();
041      // Preserve interrupt status
042      Thread.currentThread().interrupt();
043    }
044  }
045}