Han Vo
Han Vo

Reputation: 23

Shutdown a java app (multiple threads) gracefully

I am trying to set up a shutdown hook to handle SIGTERM (kill -15). It shuts down but doesn't look like it gracefully finish up ** processing** function as it never output the log "Thread has been shutdown".

public class Runner {
    public static void main(String[] args) {
        Test test = new Test();
        Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    try {
                        logger.warn("Shutting things down..."); // This works 
                        test.stop();
                    } catch (Exception ex) {
                        logger.error("Error shutting the app gracefully", ex);
                    }
                }
            });

        test.processing();
    }
}           


public class Test {
    private volatile boolean processingExit = false;
    public void stop() {
        processingExit = true;
    }

    public void processing() {
        while (!processingExit) {
            //do work here
            logger.info("doing work... keep printing..."); //This works until I send a kill -15 signal
        }
        // This log never works
        logger.info("Thread has been shutdown"); // This doesn't works 
    } 
}

Upvotes: 2

Views: 1348

Answers (1)

Magnus
Magnus

Reputation: 8310

The problem is that as soon as the shutdown hook thread completes, the process is halted, you need to have the shutdown hook thread wait for the main thread.

Copied from https://stackoverflow.com/a/2922031/1544715

From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

Upvotes: 1

Related Questions