I am writing an application program using swing. I need to exit from the application by clicking the JButton
for that can i use System.exit()
or should i use some other methods, which is the best practice. If calling System.exit()
is not best practice then tell the reason and tell the alternative way to exit from the application.
views:
475answers:
5Personnaly, I do consider as best practice to let application exit by itself : if you write a main class with a main(String[] args)
, with empty code, running it will exit silently from Java program.
But, in most times, like most of developpers, I rely upon System.exit(/an exit code/)
, especially for Swing applications, where the Swing EDT will run endlessly, as justkt wrote.. The known drawxback of this method is that most of applciation code is not called, what I avoid by setting a shutdown hook by calling Runtime.addShutdownHook(Thread)
, which will allow me to clean application (close threads, and so on).
If you need to set an exit code for your application, you have to use System.exit (I think).
But when you do not need a specific code (or 0 is fine), then I would much rather have the JVM terminate "naturally", which happens when there are no more (non-daemon) threads left.
Usually, you would just reach the end of your main method.
I would be careful with System.exit because there may be other threads that still need to do something, and exiting without shutting them down properly may cause damage. For example the embedded database might still need to flush its buffers.
If you know about these threads, you can usually arrange for them to end gracefully. If you do not know what threads are running in your program, you have bigger problems...
System.exit can be bad at least when you have multiple threads or resources that need to be closed properly (that live outside JVM). If your application isn't exiting when you think it should then you should find out what the problem is and not just call System.exit().
The only reason for calling System.exit() would be to give some none standard exit code.
Generally speaking the only time you need to do a System.exit(n) is if you want to exit a command line program with an error code so that anything that is monitoring the program can detect the error code.
This is most useful for example, if you are writing a program designed to be run from a shell script.
As other replies say though, if you are using threads then you must make every effort to shut them down gracefully before considering a System.exit(n)
Calling System.exit() anywhere but the "main" method of an application is problematic for (at least) the following reasons.
It is an impediment to reusing your code.
It makes unit testing hard. For example, if your code calls
System.exit
when your JUnit tests exercise some error handling, that it the end of your test sequence!