我想禁止在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