Browse Source

HADOOP-15366. Add a helper shutdown routine in HadoopExecutor to ensure clean shutdown. Contributed by Shashikant Banerjee.

Mukul Kumar Singh 7 years ago
parent
commit
0b345b7653

+ 33 - 1
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/concurrent/HadoopExecutors.java

@@ -27,7 +27,7 @@ import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.SynchronousQueue;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.TimeUnit;
-
+import org.slf4j.Logger;
 
 /** Factory methods for ExecutorService, ScheduledExecutorService instances.
  * These executor service instances provide additional functionality (e.g
@@ -91,6 +91,38 @@ public final class HadoopExecutors {
     return Executors.newSingleThreadScheduledExecutor(threadFactory);
   }
 
+  /**
+   * Helper routine to shutdown a executorService.
+   *
+   * @param executorService - executorService
+   * @param logger          - Logger
+   * @param timeout         - Timeout
+   * @param unit            - TimeUnits, generally seconds.
+   */
+  public static void shutdown(ExecutorService executorService, Logger logger,
+      long timeout, TimeUnit unit) {
+    try {
+      if (executorService != null) {
+        executorService.shutdown();
+        try {
+          if (!executorService.awaitTermination(timeout, unit)) {
+            executorService.shutdownNow();
+          }
+
+          if (!executorService.awaitTermination(timeout, unit)) {
+            logger.error("Unable to shutdown properly.");
+          }
+        } catch (InterruptedException e) {
+          logger.error("Error attempting to shutdown.", e);
+          executorService.shutdownNow();
+        }
+      }
+    } catch (Exception e) {
+      logger.error("Error during shutdown: ", e);
+      throw e;
+    }
+  }
+
   //disable instantiation
   private HadoopExecutors() { }
 }