Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use main() to restart my application?

I am researching a way to restart my java application by clicking a button on the GUI. I searched the web and came across main( new String[0]). I need to understand if this is an valid way to restart my application. Can someone please advise thanks.

private void bnNewsaleActionPerformed(java.awt.event.ActionEvent evt) {

    main( new String[0]);
    }

Edit Would this be better?

private void bnNewsaleActionPerformed(java.awt.event.ActionEvent evt) {
    classname.this.dispose();
    main( new String[0]);
    }
like image 830
Adesh Avatar asked Oct 31 '12 23:10

Adesh


2 Answers

It calls the static main method with an empty string array. See if this makes it any clearer:

String[] args = new String[0]; // Or String[] args = {};
main(args);

Admittedly it's unusual to call a main method from non-main method... and this won't really "restart" the application. It will call it from within your existing handler which may well have nasty consequences. I wouldn't recommend it.

If you can work out a way to start an entirely clean process, that would be a far more reliable "restart".

like image 161
Jon Skeet Avatar answered Oct 07 '22 03:10

Jon Skeet


You're not going to be able to restart your application without exiting the JVM - the JVM will have allocated objects, threads etc. and without a lot of housekeeping you're not going to easily trash this.

I think an easier way is to wrap your application in a script, and to get the script to restart your app if it exits with a particular exit code. That way you can trash your JVM completely via a System.exit() call, and if the script only restarts your app if it sees a particular exit code, you have the option of quitting, or quitting and restarting.

e.g. check out the JavaServiceWrapper. This provides a capability to start a Java application with particular config/parameters, and to control restart behaviour. Note that it provides a particular API call to invoke a restart from within your application.

like image 25
Brian Agnew Avatar answered Oct 07 '22 02:10

Brian Agnew