Read Also: Difference between User thread and Daemon thread in Java
JVM can be terminated either in a controlled manner or an abrupt manner.
How to End Java Program
How to end Java Program in a Controlled Manner
1. Using System class
The easiest way to end the Java program is by using System.exit() method. The syntax of the System.exit() method is:
Syntax
public static void exit(int status)Parameters
int status is an integer value and indicates the status of termination as shown below:
exit(0) - Normally indicates successful termination.
exit(-1) or exit(1) or any other non-zero value – Normally indicates unsuccessful termination.
exit(-1) or exit(1) or any other non-zero value – Normally indicates unsuccessful termination.
System.exit() method makes a call to exit method in the Runtime class i.e. Runtime.getRuntime().exit(). This method call results in exiting the current program by terminating the JVM. As the name suggests, the return type of exit method is void, in other words, it does not return anything.
Throws
Exit method throws SecurityException.
Example
public class ExitDemo {
public static void main(String args[]) {
System.out.println("Executing inside main() method");
System.exit(0);
System.out.println("Finish executing main() method");
}
}Output:
Executing inside main() method
2. Using Runtime class
As stated above calling System.exit(n) is the same as making a call to Runtime.getRuntime().exit() method.
The exit method here does two things
1. First it calls the checkExit(n) method of SecurityManager class that checks whether the thread which is calling the exit method has permission to call the halt(n) method. halt() method forcibly terminates the JVM with the specified status n.
2. Secondly, it calls method exit of Shutdown class which is responsible for halting the JVM.
The exit method of the Shutdown class finishes all the registered shutdown hooks and finalizer methods associated with different classes if finalization-on-exit has been enabled.
public class ExitDemo2
{
public static void main(String[] args)
{
Runtime.getRuntime().exit(0);
}
}
What is a shutdownhook
Shutdownhook is an initialized but unstarted thread that one want to execute when System.exit() or Runtime.getRuntime().exit() is called.
public class ExitDemo3 {
public static void main(String[] args) {
Thread shutDownHook = new Thread(() ->
System.out.println("In the middle of a shutdown, calling the shutdown hook"));
// registering our defined shutdownhook
Runtime.getRuntime().addShutdownHook(shutDownHook);
System.out.println("Application is now getting terminated");
}
}In the above code, we have defined a thread using lambda which will print "In the middle of a shutdown, calling the shutdownhook" whenever it will be executed.
Note: JVM runs shutdown hooks only when the termination is happening in a controlled manner. When we will run the above code, we will see that the JVM called the shutdown hook once the main method execution is finished.
Output:
Application is now getting terminated
In the middle of a shutdown, calling the shutdown hook
3. Automatically (By itself)
When the last daemon thread running within the JVM completes, the JVM starts its shutdown process.
4. End Java Program using Operation System
a. When the machine on which the JVM is running shuts down, it will shut down all the running processes including JVM.
b. When we hit CTRL + C to stop the running program on cmd.
c. When sending an interrupt signal from the OS like SIGINT on Linux.
How to end Java Program in an Abrupt Manner
1. By Operating System
a. When the JVM process is killed explicitly using processId and the kill command.
b. By closing the command prompt(cmd) which you used to start the Java program. If before the program can complete, you close the common prompt then it will terminate the running Java program and the associated JVM.
c. By Sending an interrupt signal from the OS like SIGKILL on Linux.
2. Using Runtime class
The second method is halt(0). This method forcefully terminates the JVM and does not call any of the shutdown hooks or exit finalizers, it just terminates.
public class ExitDemo4 {
public static void main(String[] args) {
Runtime.getRuntime().halt(0);
}
}3. When an Error occurs
JVM will terminate if it encounters an error from which it can't recover. For example, any error related to memory (StackOverFlowError, OutOfMemoryError)
public class ExitDemo5 {
public static void main(String[] args) {
main(null);
}
}Output:
Exception in thread "main" java.lang.StackOverflowError
Here we are calling the main method in a recursive manner which will result in an infinite loop and will eventually terminate the JVM with an Exception 'Exception in thread "main" java.lang.StackOverflowError'.
That's all for today. Please mention in the comments if you have any questions related to how to end the program in Java.