Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke a cleanup method for java user thread, when JVM stops the thread

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.

like image 248
user309281 Avatar asked May 08 '10 06:05

user309281


1 Answers

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

like image 112
aioobe Avatar answered Oct 20 '22 01:10

aioobe