views:

87

answers:

1

Hi All

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.

+1  A: 

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.)

aioobe
Thanks for the detailed explanation. The java process runs in red hat linux OS.And in my stopApplication script, I am getting the PID of the java process (stored in a file, when starting up), and doing kill -15 (SIGTERM), sleeping for 40 sec, and then doing kill -9 of the pid.Just want to know, when kill -15 pid is executed, will the Runtime.addshutdownHook be invoked ?
Yep. `kill -15 PID` yields the same output of the java program as the output of `kill PID` (See above.)
aioobe