我想禁止在AccessController.doPriviliged()方法中创建线程。下面的方法创建并运行线程。我用-Djava.security.manager运行这个。根据这个链接,如果modifyThreadGroup没有被授予,那么线程创建应该被禁止?AccessController doPrivileged可以在modifyThreadGroup未被授予时创建线程吗?
http://docs.oracle.com/javase/7/docs/technotes/guides/security/permissions.html
谁能开导我,为什么发生这种情况,并使用AccessController的不允许线程创建正确的方法是什么?
// .java.policy in $UserHome:
grant codeBase "file:/C:/-" {
permission java.security.AllPermission;
};
public class ThreadTest {
public void testModifyThreadGroup() {
// grant no permissions
Permissions perms = new Permissions();
ProtectionDomain domain = new ProtectionDomain(
new CodeSource(null, (Certificate[]) null), perms);
AccessControlContext _accessControlContext = new AccessControlContext(
new ProtectionDomain[] { domain });
try {
AccessController.doPrivileged(new PrivilegedExceptionAction(){
@Override
public Object run() {
try {
// modifyThreadGroup not granted, so should not be able
// to call Thread constructor???
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread.run()");
}
});
t.run();
} catch (Exception ex) {
System.out.println("Error running thread: " + ex);
}
return null;
}}, _accessControlContext);
} catch(Exception e) {
System.out.println("Access Error running doPrivileged: " + e);
}
}
}
谢谢!从你链接的文档中:“需要更严格策略的应用程序应该重写此方法,如果重写此方法,则重写该方法的方法应另外检查调用线程是否具有RuntimePermission(”modifyThreadGroup“)权限,如果所以,请静静地返回。这是为了确保授予该权限的代码(如JDK本身)可以处理任何线程。“我发现在相关方法中检查'modifyThread'和'modifyThreadGroup'(检查'exitVM'的地方)给出了期望的行为。 – markt