美文网首页
优雅关闭ExecutorService

优雅关闭ExecutorService

作者: 三云_16d2 | 来源:发表于2018-12-26 13:57 被阅读0次
public static void gracefulShutdown(long timeout, TimeUnit unit, ExecutorService... executorServices) {
        for (ExecutorService executorService: executorServices) {
            executorService.shutdown();
        }

        boolean wasInterrupted = false;
        final long endTime = unit.toMillis(timeout) + System.currentTimeMillis();
        long timeLeft = unit.toMillis(timeout);
        boolean hasTimeLeft = timeLeft > 0L;

        for (ExecutorService executorService: executorServices) {
            if (wasInterrupted || !hasTimeLeft) {
                executorService.shutdownNow();
            } else {
                try {
                    if (!executorService.awaitTermination(timeLeft, TimeUnit.MILLISECONDS)) {
                        LOG.warn("ExecutorService did not terminate in time. Shutting it down now.");
                        executorService.shutdownNow();
                    }
                } catch (InterruptedException e) {
                    LOG.warn("Interrupted while shutting down executor services. Shutting all " +
                            "remaining ExecutorServices down now.", e);
                    executorService.shutdownNow();

                    wasInterrupted = true;

                    Thread.currentThread().interrupt();
                }

                timeLeft = endTime - System.currentTimeMillis();
                hasTimeLeft = timeLeft > 0L;
            }
        }
    }

相关文章

网友评论

      本文标题:优雅关闭ExecutorService

      本文链接:https://www.haomeiwen.com/subject/omjhlqtx.html