I want to restart a java application when it is stopped. This stackoverflow question addresses how to start a java application.
Is it possible to make a program restart itself when it is shutdown? Or save its state before exiting?
My first approach was trying to run a thread passing the following Runnable
implementation:
public void run() {
try {
while(true) {
// perform important computations
}
}
catch(Throwable t) {
// save state before exiting and start again
System.out.println("saving...");
}
}
This did not work, because when I press Ctrl+C the program produces no output, which means that any code with a ProcessBuilder
will not run too.
In case it's not possible, how can I keep an application running (either stop it from being shutdown and/or start it again once it's shutdown) using other programming languages or using operating system settings (e.g. UNIX)?
Update: I used pens-fan-69's code along with a ProcessBuilder
instance. For reference, here's how the code looks:
public class Unkillable {
public static void main(String[] args) {
System.out.println("I'm running!");
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread() {
@Override
public void run() {
// save state before exiting and start again
System.out.println("Shuting down...");
ProcessBuilder pb = new ProcessBuilder("java", "Unkillable");
try {
pb.start();
} catch (IOException e) {
System.out.println("Error executing callback function.");
}
}
});
while(true) {
// fancy code goes here
}
}
}
This comes with a side effect: when you run this on a console, hitting Ctrl+C will make the program invisible, running in the background. I was then able to kill the remaining process via the activity monitor. If this class received input from the user, this would be of little use. I wonder if there's anyway to associate the new process with a console or something similar.