+
+ /**
+ * Tries to shutdown the given executor gracefully by awaiting termination for the given
+ * timeout period. If the timeout elapses before termination, the executor is forcefully
+ * shutdown.
+ */
+ public static void tryGracefulShutdown(final ExecutorService executor, long timeout,
+ TimeUnit unit ) {
+
+ executor.shutdown();
+
+ try {
+ if (!executor.awaitTermination(timeout, unit)) {
+ executor.shutdownNow();
+ }
+ } catch( InterruptedException e ) {
+ executor.shutdownNow();
+ }
+ }