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?
Strictly speaking, a Java program cannot restart itself since to do so it must kill the JVM in which it is running and then start it again, but once the JVM is no longer running (killed) then no action can be taken.
It can be done relatively easily by moving your code out into a separate method, and then calling that method over and over again... The main() method just controls the repeating of your program. All the other questions and processing occurs in the runMyCode() method.
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
If it's as simple as this, you can simply use a shutdownhook.
Runtime.getRuntime().addShutdownHook(() -> {
//do whatever you want to be done when closing the program here
});
Though you might encounter some problems, if you want to restart the program and use the same commandline.
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