How to shutdown an ExecutorService?

前端 未结 2 1989
梦毁少年i
梦毁少年i 2020-11-27 02:52

Whenever I call shutdownNow() or shutdown() it doesn\'t shut down. I read of a few threads where it said that shutting down is not guaranteed - can

2条回答
  •  余生分开走
    2020-11-27 03:17

    The best way is what we actually have in the javadoc which is:

    The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:

    void shutdownAndAwaitTermination(ExecutorService pool) {
        pool.shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(60, TimeUnit.SECONDS))
                    System.err.println("Pool did not terminate");
            }
        } catch (InterruptedException ie) {
            // (Re-)Cancel if current thread also interrupted
            pool.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }
    

提交回复
热议问题