'AccessController.doPrivileged usage

I'm trying to understand how to use correctelly AccessController.doPrivileged().

I have:

  • A password file, named store.pwd

  • A policy file, named policy.policy

    grant {
       permission java.io.FilePermission "store.pwd", "read";
    };
    

I have implemented 2 Thread:

  1. The first one:
  • Set the policy file System.setProperty("java.security.policy", "policy.policy");
  • Install the default Security Manager System.setSecurityManager(new SecurityManager());
  • Read lines from store.pwd
  • Operation allowed
  1. The second one:
  • Install the default Security Manager System.setSecurityManager(new SecurityManager());
  • Read lines from store.pwd
  • Operation not allowed
  1. If from Thread1 I call Thread2:
  • Operation allowed

If every time I invoke unauthorized code from authorized code, the unauthorized code inherits the permissions of the protection domain of the caller and the opperation succeeds, in which case is it necessary to use doPrivileged?

From the documentation:

public static T doPrivileged(PrivilegedAction action)

Performs the specified PrivilegedAction with privileges enabled. The action is performed with all of the permissions possessed by the caller's protection domain.

But from the tests shown above it seems that this operation is automatic, so another time, in which case is it necessary to use doPrivileged?

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source