在 interrupt()类的方法Thread ,我们有checkAccess调用它又调用 SecurityManager#checkAccess(Thread) 。现在,考虑 SecurityManager.checkAccess(Thread)
方法的来源:
public void checkAccess(Thread t) {
if (t == null) {
throw new NullPointerException("thread can't be null");
}
if (t.getThreadGroup() == rootGroup) { //1
checkPermission(SecurityConstants.MODIFY_THREAD_PERMISSION);
} else {
// just return
}
}
在//1
处,我们会比较线程是否属于根组,如果不属于根组,我们不会应用SecurityManager
实例提供的访问规则。因此,我编写了以下示例:
public static void main (String[] args) throws java.lang.Exception
{
Thread t = new Thread();
System.out.println(t.getThreadGroup()); //prints java.lang.ThreadGroup[name=main,maxpri=10]
System.out.println(t.getThreadGroup().getParent()); //prints java.lang.ThreadGroup[name=system,maxpri=10]
}
并发现使用Thread
的构造函数创建的线程不属于rootGroup
。因此,java.policy
文件中指定的权限(特别是)永远不会应用于我们自己创建的线程。
这有什么原因吗?我的意思是,将权限应用于唯一的根组?
最佳答案
我猜想,允许线程中断等非系统线程的线程通常是安全的(不是安全问题)。
请注意,javadoc 是这样说的:
"If the thread argument is a system thread (belongs to the thread group with a null parent) then this method calls checkPermission with the RuntimePermission("modifyThread") permission. If the thread argument is not a system thread, this method just returns silently."
"Applications that want a stricter policy should override this method. ....."
关于java - 为什么访问规则不适用于非根组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805474/