I have J2SE application running in linux. I have stop application script in which i am doing kill of the J2SE pid. This J2SE application has 6 infinitely running user threads,which will be polling for some specific records in backend DB.
When this java pid is killed, I need to perform some cleanup operations for each of the long running thread, like connecting to DB and set status of some transactions which are in-progress to empty.
Is there a way to write a method in each of the thread, which will be called when the thread is going to be stopped, by JVM.
You can always try to implement a shut down hook using Runtime.addShutDownHook, or encapsulate the long-running-code in a try and the cleanup in finally.
A minimal example doing roughly what you want to do (but for a single worker thread for simplicity).
public class Test extends Thread {
    static volatile boolean keepRunning = true;
    public static void main(String[] args) throws InterruptedException {
        final Thread t = new Test();
        t.start();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                System.out.println("Shutting down...");
                keepRunning = false;
                t.interrupt();
                try {
                    t.join();
                } catch (InterruptedException e) {
                }
            }
        });
    }
    public void run() {
        while (keepRunning) {
            System.out.println("worknig...");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
            }
        }
        System.out.println("cleaning up.");
    }
}
Output when interrupting with Ctrl-C:
worknig...
worknig...
worknig...
^CShutting down...
cleaning up.
Output when killing with kill pid
worknig...
worknig...
worknig...
worknig...
Shutting down...
cleaning up.
Output when killing with kill -9 pid
worknig...
worknig...
worknig...
worknig...
worknig...
Killed
(No cleanup executed.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With