THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

privileged while obtaining the fonts.


The doPrivileged method of AccessController take as an argument a
java.security.PrivilegedAction object whose run method defines the code to be marked as
privileged. For example, your call to doPrivileged can look like the following:


void someMethod() {
// ...normal code here...
AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
// privileged code goes here, for example:
System.loadLibrary("awt");
return null; // nothing to return
}
}
);
// ...normal code here...
}


The doPrivileged method executes the run method in privileged mode. Privileged execution is a way for
a class with a given permission to temporarily grant that permission to the thread that executes the privileged
code. It will not let you gain permissions that you do not already have. The class defining someMethod must
have the permission RuntimePermission("loadLibrary.awt"); otherwise, any thread that invokes
someMethod will get a SecurityException. It is guaranteed that privileges will be revoked after the
PrivilegedAction object's run method returns.


The PrivilegedAction interface's single method run returns a T object. Another form of
doPrivileged takes a PrivilegedExceptionAction object, whose run method also returns
T, but which can throw any checked exception. For both of these methods there is a second overloaded form
of doPrivileged that takes an AccessControlContext as an argument and uses that context to
establish the permissions that the privileged code should run with.


You should use doPrivileged with extreme care and ensure that your privileged sections of code are no
longer than necessary and that they perform only actions you fully control. For example, it would be an
extreme security risk for a method with, say, all I/O permissions, to accept a Runnable argument and invoke
its run method within a privileged section of code, unless you wouldn't mind if that method removed all the
files on your disk.


Power corrupts. Absolute power is kind of neat.

John Lehman, U.S. Secretary of the Navy, 19811987

Chapter 24. Internationalization and Localization


Nobody can be exactly like me. Sometimes even I have trouble doing it.

Tallulah Bankhead

The credo of "Write once, run anywhere™" means that your code will run in many places where languages
and customs are different from yours. With a little care you can write programs that can adapt to these
variations gracefully. Keeping your programs supple in this fashion is called internationalization. You have
several tools for internationalizing your code. Using internationalization tools to adapt your program to a