View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.util;
18  
19  import java.util.concurrent.ExecutorService;
20  import java.util.concurrent.TimeUnit;
21  
22  import org.apache.logging.log4j.Logger;
23  import org.apache.logging.log4j.status.StatusLogger;
24  
25  public class ExecutorServices {
26  
27      private static final Logger LOGGER = StatusLogger.getLogger();
28  
29      /**
30       * Shuts down the given {@link ExecutorService} in an orderly fashion. Disables new tasks from submission and then
31       * waits for existing tasks to terminate. Eventually cancels running tasks if too much time elapses.
32       * <p>
33       * If the timeout is 0, then a plain shutdown takes place.
34       * </p>
35       *
36       * @param executorService
37       *            the pool to shutdown.
38       * @param timeout
39       *            the maximum time to wait, or 0 to not wait for existing tasks to terminate.
40       * @param timeUnit
41       *            the time unit of the timeout argument
42       * @param source
43       *            use this string in any log messages.
44       * @return {@code true} if the given executor terminated and {@code false} if the timeout elapsed before
45       *         termination.
46       */
47      public static boolean shutdown(final ExecutorService executorService, final long timeout, final TimeUnit timeUnit, final String source) {
48          if (executorService == null || executorService.isTerminated()) {
49              return true;
50          }
51          executorService.shutdown(); // Disable new tasks from being submitted
52          if (timeout > 0 && timeUnit == null) {
53              throw new IllegalArgumentException(
54                      String.format("%s can't shutdown %s when timeout = %,d and timeUnit = %s.", source, executorService,
55                              timeout, timeUnit));
56          }
57          if (timeout > 0) {
58              try {
59                  // Wait a while for existing tasks to terminate
60                  if (!executorService.awaitTermination(timeout, timeUnit)) {
61                      executorService.shutdownNow(); // Cancel currently executing tasks
62                      // Wait a while for tasks to respond to being cancelled
63                      if (!executorService.awaitTermination(timeout, timeUnit)) {
64                          LOGGER.error("{} pool {} did not terminate after {} {}", source, executorService, timeout,
65                                  timeUnit);
66                      }
67                      return false;
68                  }
69              } catch (final InterruptedException ie) {
70                  // (Re-)Cancel if current thread also interrupted
71                  executorService.shutdownNow();
72                  // Preserve interrupt status
73                  Thread.currentThread().interrupt();
74              }
75          } else {
76              executorService.shutdown();
77          }
78          return true;
79      }
80  
81  }