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