Reputation: 21
Can anyone explain this code of HackerRank?
class DoNotTerminate {
public static class ExitTrappedException extends SecurityException {
private static final long serialVersionUID = 1;
}
public static void forbidExit() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
}
This following code will stop you from terminating the code using exit(0)!
Upvotes: 2
Views: 1591
Reputation: 206816
When a program tries to stop the JVM by calling System.exit(...)
, then it first checks if this action is allowed by asking the security manager if the exitVM
permission is granted.
The code you posted replaces the security manager with a custom security manager that will throw an ExitTrappedException
when checking for the exitVM
permission.
So, what happens is this:
System.exit(...)
System.exit(...)
method asks the security manager if the exitVM
permission is allowedExitTrappedException
System.exit(...)
does not continue to stop the JVM, but passes the exception on the caller; the JVM keeps runningUpvotes: 3