Q:

How to exit gracefully a java application?

I have a java application which runs some function periodically using Executors.newSingleThreadScheduledExecutor
In the main() function I'm waiting forever using:
Thread.currentThread().join();

Can the java application identify that it's being closed (i.e. by Ctrl-C, Ctrl-D signals), particularly, the thread running the scheduled task?
The idea is to gracefully close the application.

A:

Register a shutdown hook with the Java Runtime. The shutdown of JVM will be notified on the registered thread. Below is an example:
public class Main {

    public static void main(String[] args) {

        Runtime.getRuntime().addShutdownHook(new ShutDownHookThread());

        while (true) {

        }

    }

}

class ShutDownHookThread extends Thread {
    @Override
    public void run() {
       // ***write your code here to handle any shutdown request
        System.out.println("Shut Down Hook Called");
        super.run();
    }
}

