System.exit() terminates the Java Virtual Machine (JVM), consequently terminating all running programs and threads. This can result in denial-of-service (DoS) attacks. For example, a call to
System.exit() that is embedded in Java Server Pages (JSP) code can cause a web server to terminate, preventing further service for users. Programs must prevent both inadvertent and malicious calls to
System.exit(). Additionally, programs should perform necessary cleanup actions when forcibly terminated (for example, by using the Windows Task Manager, POSIX
kill command, or other mechanisms).
Noncompliant Code Example
This noncompliant code example uses
System.exit() to forcefully shut down the JVM and terminate the running process. The program lacks a security manager; consequently, it lacks the capability to check whether the caller is permitted to invoke
This compliant solution installs a custom security manager
PasswordSecurityManager that overrides the
checkExit() method defined in the
SecurityManager class. This override is required to enable invocation of cleanup code before allowing the exit. The default
checkExit() method in the
SecurityManager class lacks this facility.
This implementation uses an internal flag to track whether the exit is permitted. The method
setExitAllowed() sets this flag. The
checkExit() method throws a
SecurityException when the flag is unset (that is, false). Because this flag is not initially set, normal exception processing bypasses the initial call to
System.exit(). The program catches the
SecurityException and performs mandatory cleanup operations, including logging the exception. The
System.exit() method is enabled only after cleanup is complete.
Allowing unauthorized calls to
System.exit() may lead to denial of service.
Debug Call (Java)
|Do not stop the JVM in a web component|
Do not call methods which terminates Java Virtual Machine
|S1147||Exit methods should not be called|
Android Implementation Details
System.exit() should not be used because it will terminate the virtual machine abruptly, ignoring the activity life cycle, which may prevent proper garbage collection.
Section 9.5, "The Finalize Method"
Rule 78, Restrict the use of the
Section 7.4, "JVM Shutdown"
Chapter 16, "Intercepting a Call to