I have a Java program that I want to be able to automatically restart (say, in the event of a detected fatal error, the user has the choice to restart or quit). How can I do this?
            Asked
            
        
        
            Active
            
        
            Viewed 2,785 times
        
    0
            
            
        - 
                    look at http://stackoverflow.com/questions/11906769/java-restartapplication-method-only-restarts-once?rq=1 – Pascal Le Merrer Mar 11 '14 at 16:44
- 
                    How would you know that you had a fatal error? The VM would exit, right? You could spawn a small helper application that starts when you're application starts and periodically checks on the main application, restarting it when necessary. You could also install an application as a service (in Windows) or equivalent in other OSs. But I think you should be thinking on the model of "fail, don't resume." You should try to understand why a program failed before simply restarting. – mttdbrd Mar 11 '14 at 16:47
- 
                    1Depending on your requirements you might find http://serverfault.com/questions/83963/alternatives-to-nagios useful for a discussion on some external monitoring applications, for example [Shinken](http://www.shinken-monitoring.org/) – andyb Mar 11 '14 at 16:52
1 Answers
0
            
            
        You cannot recover from a real fatal Error, launched by the JVM. You can recover from an Exception launched by your own program, but I cannot imagine when just restarting the application is a good solution. An elegant recovery should include treat each issue differently: You cannot find a file? Ask the user for the proper path. You cannot connect to internet? Give a second try option to the user, just in case he forgot to turn on the wifi... and so on.
Said that, that's my proposal: You have to catch the error and then just call the initial method:
public class Example {
    ...
    public static void main(String[] args) {
        boolean exit=false;
        while(!exit) {
            try {
               runMyProgram(args);
            } catch (Exception e) {
               exit=askIfTerminateOrNot();
            }
        }
     }
    ... //Needed methods
}
But as I said before, I would not implement this solution.
 
    
    
        Pablo Lozano
        
- 10,122
- 2
- 38
- 59
