3

Can an executable jar file can restart itself? For instance, after a user made some choice, the program says "Restart the app?" and the user clicks "Yes" then the jar shuts down and restarts itself.

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
Frank
  • 30,590
  • 58
  • 161
  • 244
  • Sounds like maybe you need two apps: one to edit the config file, and the actual app itself. – TMN Jun 10 '10 at 14:24

2 Answers2

3

Needing to restart an application is a sign of bad design.

I would definitely try hard to be able to "reinitialize" the application (reread config files, reestablish connections or what ever) instead of forcing the user to terminate / start the application (even if it's done automatically).

A half-way "hack" would be to encapsulate your application in some runner-class that's implements something like:

public class Runner {
    public static void main(String... args) {
        while (true) {
            try {
                new YourApplication().run();
                return;
            } catch (RestartException re) {
            }
        }
    }
}
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • So in my situation, I want a server application to re-start itself whenever its jar file is changed. For updating the service jar. Without involving a whole update system and multiple loaders and other jars. I know that it is not possible to replace a .jar file in Windows that is currently run by the VM. But on most ***x systems it has worked so far; thus I wanna take advantage of that – JayC667 May 06 '17 at 12:49
  • I think a launch script along the lines of "while true, launch jar in background, watch for changes on jar, if it changes, kill process, end while" would make more sense than to try to bake this functionality into the program itself. – aioobe May 06 '17 at 13:19
2

Well, if you know the location of the Jar file on the file system, you could programatically run the Jar. And then exit the currently running version.

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("java -jar locatio/of/the/jar");
System.exit(0);
jjnguy
  • 136,852
  • 53
  • 295
  • 323