20 August 2022
In Java, such as many others pragramming language, it is possibile to implement an exit gracefully from a program.
Note: I created a repository with a full example --> https://gitlab.com/ipsedixit-org/java-exit-gracefully-example
There two concept explained in this post:
In hava there is a special instruction used to force a program to end immediately and it is:
System.exit(exitValue);
Where:
Calling System.exit
interrupt immediately the program and the are no more instruction execute, neither inside finally.
Example:
try {
System.out.println("Printed");
System.exit(exitValue);
System.out.println("Not printed");
} finally {
System.out.println("Not executed");
}
So please pay attention to use System.exit
carefully because could create a memory leak on opened resources.
It is possible to register a shutdown hook using Runtime.getRuntime().addShutdownHook(...)
.
The Java virtual machine shuts down in response to two kinds of events:
A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method.