When should we call System.exit in Java
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?
System.exit()
can be used to run shutdown hooks before the program quits. This is a convenient way to handle shutdown in bigger programs, where all parts of the program can't (and shouldn't) be aware of each other. Then, if someone wants to quit, he can simply call System.exit()
, and the shutdown hooks (if properly set up) take care of doing all necessary shutdown ceremonies such as closing files, releasing resources etc.
"This method never returns normally." means just that the method won't return; once a thread goes there, it won't come back.
Another, maybe more common, way to quit a program is to simply to reach the end of the main
method. But if there are any non-daemon threads running, they will not be shut down and thus the JVM will not exit. Thus, if you have any such non-daemon threads, you need some other means (than the shutdown hooks) to shut down all non-daemon threads and release other resources. If there are no other non-daemon threads, returning from main
will shut down the JVM and will call the shutdown hooks.
For some reason shutdown hooks seem to be an undervalued and misunderstood mechanism, and people are reinventing the wheel with all kind of proprietary custom hacks to quit their programs. I would encourage using shutdown hooks; it's all there in the standard Runtime that you'll be using anyway.
In that case, it's not needed. No extra threads will have been started up, you're not changing the exit code (which defaults to 0) - basically it's pointless.
When the docs say the method never returns normally, it means the subsequent line of code is effectively unreachable, even though the compiler doesn't know that:
System.exit(0);
System.out.println("This line will never be reached");
Either an exception will be thrown, or the VM will terminate before returning. It will never "just return".
It's very rare to be worth calling System.exit()
IME. It can make sense if you're writing a command line tool, and you want to indicate an error via the exit code rather than just throwing an exception... but I can't remember the last time I used it in normal production code.
The method never returns because it's the end of the world and none of your code is going to be executed next.
Your application, in your example, would exit anyway at the same spot in the code, but, if you use System.exit. you have the option of returning a custom code to the enviroment, like, say
System.exit(42);
Who is going to make use of your exit code? A script that called the application. Works in Windows, Unix and all other scriptable environments.
Why return a code? To say things like "I did not succeed", "The database did not answer".
To see how to get the value od an exit code and use it in a unix shell script or windows cmd script, you might check this answer on this site
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).
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. Calling System.exit
will initiate the program's shutdown hooks and whatever thread that calls System.exit
will block until program termination. This has the implication that if the shutdown hook in turn submits a task to the thread from which System.exit
was called, the program will deadlock.
I'm handling this in my code with the following:
public static void exit(final int status) {
new Thread("App-exit") {
@Override
public void run() {
System.exit(status);
}
}.start();
}
One should NEVER call System.exit(0)
for these reasons:
- It is a hidden "goto" and "gotos" break the control flow. Relying on hooks in this context is a mental mapping every developer in the team has to be aware of.
Quitting the program "normally" provides the same exit code to the operating system as
System.exit(0)
so it is redundant.If your program cannot quit "normally" you have lost control of your development [design]. You should have always full control of the system state.
- Programming problems such as running threads that are not stopped normally become hidden.
- You may encounter an inconsistent application state interrupting threads abnormally. (Refer to #3)
By the way: Returning other return codes than 0 does make sense if you want to indicate abnormal program termination.
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:
- In an orderly* shutdown, the JVM first starts all registered shutdown hooks. Shutdown hooks are unstarted threads that are registered with Runtime.addShutdownHook.
- JVM makes no guarantees on the order in which shutdown hooks are started. If any application threads (daemon or nondaemon) are still running at shutdown time, they continue to run concurrently with the shutdown process.
- When all shutdown hooks have completed, the JVM may choose to run finalizers if runFinalizersOnExit is true, and then halts.
- JVM makes no attempt to stop or interrupt any application threads that are still running at shutdown time; they are abruptly terminated when the JVM eventually halts.
- If the shutdown hooks or finalizers don’t complete, then the orderly shutdown process “hangs” and the JVM must be shut down abruptly.
- In an abrupt shutdown, the JVM is not required to do anything other than halt the JVM; shutdown hooks will not run.
PS: The JVM can shut down in either an orderly or abrupt manner.
- An orderly shutdown is initiated when the last “normal” (nondaemon) thread terminates, someone calls System.exit, or by other platform-specific means (such as sending a SIGINT or hitting Ctrl-C).
- While above is the standard and preferred way for the JVM to shut down, it can also be shut down abruptly by calling Runtime.halt or by killing the JVM process through the operating system (such as sending a SIGKILL).
System.exit is needed
- when you want to return a non-0 error code
- when you want to exit your program from somewhere that isn't main()
In your case, it does the exact same thing as the simple return-from-main.
Java Language Specification says that
Program Exit
A program terminates all its activity and exits when one of two things happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.
It means that You should use it when You have big program (well, at lest bigger than this one) and want to finish its execution.
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?
精彩评论