Midnight sun
Midnight sun

Reputation: 21

Java Security class to prevent you from terminating the code using exit(0)! in HackerRank

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

Answers (1)

Jesper
Jesper

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:

  1. User program calls System.exit(...)
  2. The System.exit(...) method asks the security manager if the exitVM permission is allowed
  3. The custom security manager throws an ExitTrappedException
  4. System.exit(...) does not continue to stop the JVM, but passes the exception on the caller; the JVM keeps running

Upvotes: 3

Related Questions