img
. .
System.setSecurityManager(new SecurityManager());
ThreadGroup group = Thread.currentThread().getThreadGroup();
// This line could generate a security exception
group.getParent();
}
}
The reason that this example throws a security exception is due to the
ThreadGroup.getParent() method. This method calls the ThreadGroup.checkAccess()
method, which in turn calls into the SecurityManager, which in turn calls into the new Java 2
security mechanism with the "modifyThreadGroup" permission request. If you have not given
the security mechanism permission for "modifyThreadGroup," it throws an exception. You
might wonder why an exception is thrown just for calling the getParent() method. The reason
is that by calling the getParent() method in the example, you are trying to gain a reference a
thread group that your program does not control.
In most cases, thread security is controlled by the checkAccess() methods in the Thread and
ThreadGroup classes. The checkAccess() method in the Thread class actually calls into the
security mechanism with the "modifyThread" permission, and the checkAccess() method in
the ThreadGroup class calls in to the security mechanism with the "modifyThreadGroup"
permission. Both of the checkAccess() methods are most often called by other methods in the
Thread and ThreadGroup classes.
So how does all of this affect your programs? Well, if you are simply creating and operating with
threads and thread groups in your program, you should never have to deal with security in your
program. If, however, you are trying to access or modify threads or thread groups that are not
under your control, you may run into the security system. If you are not sure if a call you are
making is going to run into the security system, the safe thing to do is enclose the section of code
you are unsure of with a try/catch block. This will allow you to catch the security exception and
then perform some sort of correction to the problem.
To help you understand what methods perform security checks, Table 10-1 lists the Thread class
methods that may cause a security check to be performed.
Table 10-1. Thread Class Methods That May Cause a Security Check
Thread class method
RuntimePermission target
getContextClassLoader()
"getClassLoader"
setContextClassLoader()
"setContextClassLoader"
checkAccess()
"modifyThread"
interrupt()
"modifyThread"
suspend()
"modifyThread"
resume()
"modifyThread"
setPriority()
"modifyThread"
setName()
"modifyThread"
setDaemon()
"modifyThread"
enumerate()
"modifyThreadGroup"
stop()
"modifyThread", "stopThread"
Thread()
"modifyThreadGroup"
Table 10-2 lists the ThreadGroup class methods that may cause a security check.
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home