[java] 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?

This question is related to java exit

The answer is


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:

  1. In an orderly* shutdown, the JVM first starts all registered shutdown hooks. Shutdown hooks are unstarted threads that are registered with Runtime.addShutdownHook.
  2. 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.
  3. When all shutdown hooks have completed, the JVM may choose to run finalizers if runFinalizersOnExit is true, and then halts.
  4. 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.
  5. If the shutdown hooks or finalizers don’t complete, then the orderly shutdown process “hangs” and the JVM must be shut down abruptly.
  6. 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.

  1. 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).
  2. 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).

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();
}

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


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.


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?


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.


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).


One should NEVER call System.exit(0) for these reasons:

  1. 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.
  2. 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.

  3. Programming problems such as running threads that are not stopped normally become hidden.
  4. 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.


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.