In Java, What is the difference with or without System.exit(0)
in following code?
public class TestExit
{
public static void main(String[] args)
{
System.out.println("hello world");
System.exit(0); // is it necessary? And when it must be called?
}
}
The document says: "This method never returns normally." What does it mean?
Though answer was really helpful but some how it missed some more extra detail. I hope below will help understand the shutdown process in java, in addition to the answer above:
PS: The JVM can shut down in either an orderly or abrupt manner.
If you have another program running in the JVM and you use System.exit, that second program will be closed, too. Imagine for example that you run a java job on a cluster node and that the java program that manages the cluster node runs in the same JVM. If the job would use System.exit it would not only quit the job but also "shut down the complete node". You would not be able to send another job to that cluster node since the management program has been closed accidentally.
Therefore, do not use System.exit if you want to be able to control your program from another java program within the same JVM.
Use System.exit if you want to close the complete JVM on purpose and if you want to take advantage of the possibilities that have been described in the other answers (e.g. shut down hooks: Java shutdown hook, non-zero return value for command line calls: How to get the exit status of a Java program in Windows batch file).
Also have a look at Runtime Exceptions: System.exit(num) or throw a RuntimeException from main?
In applications that may have complex shutdown hooks, this method should not be called from an unknown thread.
System.exit
never exits normally because the call will block until the JVM is terminated. It's as if whatever code is running that has the power plug pulled on it before it can finish. CallingSystem.exit
will initiate the program's shutdown hooks and whatever thread that callsSystem.exit
will block until program termination. This has the implication that if the shutdown hook in turn submits a task to the thread from whichSystem.exit
was called, the program will deadlock.I'm handling this in my code with the following:
System.exit(0)
terminates the JVM. In simple examples like this it is difficult to percieve the difference. The parameter is passed back to the OS and is normally used to indicate abnormal termination (eg some kind of fatal error), so if you called java from a batch file or shell script you'd be able to get this value and get an idea if the application was successful.It would make a quite an impact if you called
System.exit(0)
on an application deployed to an application server (think about it before you try it).