AccessController.doPrivileged

21,054

It is just getting a system property. Retrieving system properties requires permissions which the calling code may not have. The doPrivileged asserts the privileges of the calling class irrespective of how it was called. Clearly, doPrivileged is something you need to be careful with.

The code quoted is the equivalent of:

String lineSeparator = java.security.AccessController.doPrivileged(
    new java.security.PrivilegedAction<String>() {
        public String run() {
            return System.getProperty("line.separator");
        }
    }
 );

(Don't you just love the conciseness of Java's syntax?)

Without asserting privileges, this can be rewritten as:

String lineSeparator = System.getProperty("line.separator");
Share:
21,054
Peter Kofler
Author by

Peter Kofler

Code Cop Fanatic About Code Quality. Developing Quality Software Developers.

Updated on July 17, 2022

Comments

  • Peter Kofler
    Peter Kofler almost 2 years

    I am trying to figure out what some legacy code is doing. What exactly is this line doing, and why would I need it this way?

    String lineSeparator = (String) java.security.AccessController.doPrivileged(
           new sun.security.action.GetPropertyAction("line.separator")); 
    

    I found it in the logger implementation of the web/ejb application running on Weblogic 8. There are no special security policies enabled as far as I know. (I do not like imports from sun.* packages, so I want to get rid of this line ;-)

  • Gili
    Gili about 14 years
    @Tom, "The doPrivileged asserts the privileges of the calling class irrespective of how it was called." What does that mean? Can you give an example?
  • Brett
    Brett about 14 years
    I think I meant irrespective of the permissions of the current access control context. So usually when you call a trusted method, the permissions available to that method are those that it was called with. doPrivileged starts afresh (although it does include the permission restrictions of the immediate caller).