Graceful shutdown of threads and executor

前端 未结 5 1515
一个人的身影
一个人的身影 2020-11-29 18:42

The following piece of code tries to accompolish this.

The code loops forever and checks if there are any pending requests to be processed. If there is any, it creat

5条回答
  •  星月不相逢
    2020-11-29 19:25

    A typical orderly shutdown of an ExecutorService might look something like this:

    final ExecutorService executor;
    
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            executor.shutdown();
            if (!executor.awaitTermination(SHUTDOWN_TIME)) { //optional *
                Logger.log("Executor did not terminate in the specified time."); //optional *
                List droppedTasks = executor.shutdownNow(); //optional **
                Logger.log("Executor was abruptly shut down. " + droppedTasks.size() + " tasks will not be executed."); //optional **
            }
        }
    });
    

    *You can log that the executor still had tasks to process after waiting the time you were willing to wait.
    **You can attempt to force the executor's worker Threads to abandon their current tasks and ensure they don't start any of the remaining ones.

    Note that the solution above will work when a user issues an interrupt to your java process or when your ExecutorService only contains daemon threads. If, instead, the ExecutorService contains non-daemon threads that haven't completed, the JVM won't try to shutdown, and therefore the shutdown hooks won't be invoked.

    If attempting to shutdown a process as part of a discrete application lifecycle (not a service) then shutdown code should not be placed inside a shutdown hook but at the appropriate location where the program is designed to terminate.

提交回复
热议问题