public void runWithPermissions(Runnable r,Permission... permissions){
  SecurityManager sm=System.getSecurityManager();
  if (sm == null) {
    r.run();
    Policy savedPolicy=Policy.getPolicy();
    try {
      Policy.setPolicy(permissivePolicy());
      System.setSecurityManager(new SecurityManager());
      runWithPermissions(r,permissions);
    }
  finally {
      System.setSecurityManager(null);
      Policy.setPolicy(savedPolicy);
    }
  }
 else {
    Policy savedPolicy=Policy.getPolicy();
    AdjustablePolicy policy=new AdjustablePolicy(permissions);
    Policy.setPolicy(policy);
    try {
      r.run();
    }
  finally {
      policy.addPermission(new SecurityPermission("setPolicy"));
      Policy.setPolicy(savedPolicy);
    }
  }
}

public void runWithPermissions ( Runnable r , Permission ... permissions ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm == null ) { r . run ( ) ; Policy savedPolicy = Policy . getPolicy ( ) ; try { Policy . setPolicy ( permissivePolicy ( ) ) ; System . setSecurityManager ( new SecurityManager ( ) ) ; runWithPermissions ( r , permissions ) ; } finally { System . setSecurityManager ( null ) ; Policy . setPolicy ( savedPolicy ) ; } } else { Policy savedPolicy = Policy . getPolicy ( ) ; AdjustablePolicy policy = new AdjustablePolicy ( permissions ) ; Policy . setPolicy ( policy ) ; try { r . run ( ) ; } finally { policy . addPermission ( new SecurityPermission ( "setPolicy" ) ) ; Policy . setPolicy ( savedPolicy ) ; } } }
runs runnable r with a security policy that permits precisely the specified permissions . if there is no current security manager , the runnable is run twice , both with and without a security manager . we require that any security manager permit getpolicy / setpolicy .
