I have no way to explain this one, but I found this phenomenon in somebody else\'s code:
import java.io.IOException;
import java.io.UncheckedIOException;
imp
Your worrying about AccessController.doPrivileged
is unnecessary. It does not reduce the security if done right. The versions taking a single action argument will execute the action in your context, ignoring your callers but there are overloaded methods, having an additional argument, a previously recorded context:
private void doTest(boolean parallel)
{
Consumer createFile=name -> {
try {
Files.createTempFile(name, ".dat");
}
catch (IOException e) {
throw new UncheckedIOException("Failed to create temp file", e);
}
}, actualAction;
Stream stream = Stream.of("1", "2", "3");
if(parallel)
{
stream = stream.parallel();
AccessControlContext ctx=AccessController.getContext();
actualAction=name -> AccessController.doPrivileged(
(PrivilegedAction>)()->{ createFile.accept(name); return null; }, ctx);
}
else actualAction = createFile;
stream.forEach(actualAction);
}
The first important line is the AccessControlContext ctx=AccessController.getContext();
statement it records your current security context which includes your code and the current callers. (Remember that the effective permissions are the intersection of the sets of all callers). By providing the resulting context object ctx
to the doPrivileged
method within the Consumer
you are reestablishing the context, in other words, the PrivilegedAction
will have the same permissions as in your single-threaded scenario.