...
This noncompliant code example uses System.exit()
to forcefully shutdown 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 System.exit()
.
Code Block | ||
---|---|---|
| ||
public class InterceptExit {
public static void main(String[] args) {
// ...
System.exit(1); // Abrupt exit
System.out.println("This never executes");
}
}
|
...
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.
Code Block | ||
---|---|---|
| ||
class PasswordSecurityManager extends SecurityManager {
private boolean isExitAllowedFlag;
public PasswordSecurityManager(){
super();
isExitAllowedFlag = false;
}
public boolean isExitAllowed(){
return isExitAllowedFlag;
}
@Override
public void checkExit(int status) {
if (!isExitAllowed()) {
throw new SecurityException();
}
super.checkExit(status);
}
public void setExitAllowed(boolean f) {
isExitAllowedFlag = f;
}
}
public class InterceptExit {
public static void main(String[] args) {
PasswordSecurityManager secManager =
new PasswordSecurityManager();
System.setSecurityManager(secManager);
try {
// ...
System.exit(1); // Abrupt exit call
} catch (Throwable x) {
if (x instanceof SecurityException) {
System.out.println("Intercepted System.exit()");
// Log exception
} else {
// Forward to exception handler
}
}
// ...
secManager.setExitAllowed(true); // Permit exit
// System.exit() will work subsequently
// ...
}
}
|
...
Android Implementation Details
On Android, System.exit()
should not be used because it will terminate the virtual machine abruptly, ignoring the activity lifecycle which may prevent proper garbage collection.
Bibliography
[API 2006] | Method |
9.5, The Finalize Method | |
[ESA 2005] | Rule 78. Restrict the use of the |
7.4, JVM Shutdown | |
Chapter 16, Intercepting a Call to |
06. Exceptional Behavior (ERR) 07. Visibility and Atomicity (VNA)