Consider the following simple code that prints "Hi world" forever:
public class WakeMeUpSomehow {
public static void main(String[] args) {
while (true) {
try {
System.out.println( " Hi world ");
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
Here is the output:
Is there a way to devise an external third program , which watches this program to notice when we kill it (like with CTRL+C in command line); and then this "parent" program resumes the "Hello World" running ?
I think it might look something like this :
So my question is - how can I simulate code like this, which has this kind of fail-safe ability? Is there an way to do this?
thanks !
EDIT: I found a neat link here which is relevant but addresses something a little different- How can I restart a Java application?
Shutdown hooks are guaranteed to run on normal shutdown events of a program, but not on all kinds of abnormal termination, such as when the JVM is killed forcibly.
One solution may be to use a batch script:
@echo off
setlocal
start /wait java WakeMeUpSomehow
if errorlevel 1 goto retry
echo Finished successfully
exit
:retry
echo retrying...
start /wait java WakeMeUpSomehow