Reputation: 788
I have a Java program with an attached shutdown hook. I run it and after I kill the running process with kill <PID>
. By doing this the shutdown hook got executed and the related threads stopped immediately. But the process is still running in the background. So what could be the problem here?
Process:
javac InfiniteLoop.java
java InfiniteLoop
For PID, jps -ml | grep 'InfiniteLoop'
kill <PID>
public class InfiniteLoop {
static boolean isInfinte = true;
public static void main(String[] args) throws InterruptedException {
Thread myThread = new MyShutDownHook();
Runtime.getRuntime().addShutdownHook(myThread);
while (isInfinte) {
Thread.sleep(3000);
System.out.println("Loop is running");
}
System.out.println("Loop Exited");
myThread.interrupt();
}
}
class MyShutDownHook extends Thread {
@Override
public void run() {
System.out.print("Got Kill Message so stopping application");
InfiniteLoop.isInfinte = false;
boolean currentLoopStatus = true;
while (currentLoopStatus) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.print("Got Intteruption");
currentLoopStatus = false;
e.printStackTrace();
System.exit(0);
}
System.out.println("Child Thread Running");
}
}
}
Upvotes: 2
Views: 366
Reputation: 56
You have used System.exit(0)
in your shutdown hook thread. Remove it shutdown hook so that the process would get terminated normally. Actually System.exit(0)
itself calls shutdown internally so it could possible that code is in deadlock.
Upvotes: 4