+
+ /**
+ * 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.
+ *
+ * @param executor Executor to shut down
+ * @param timeout timeout period
+ * @param unit timeout unit
+ */
+ public static void tryGracefulShutdown(final @NonNull ExecutorService executor, final long timeout,
+ final @NonNull TimeUnit unit) {
+ executor.shutdown();
+
+ try {
+ if (!executor.awaitTermination(timeout, unit)) {
+ executor.shutdownNow();
+ }
+ } catch (InterruptedException e) {
+ executor.shutdownNow();
+ }
+ }