In addition to the security permissions provided in Java 2, you could define your own permissions
and then add the checkPermission() calls in your code. This would force the user or
administrator to define your permission in the security file in order for your program to execute.
The system security policy file (java.policy) is located in the (jre)/lib/security
directory, where (jre) is the path to the location of Java. Take a look at this file and try adding
permissions for "modifyThreadGroup" and then try running the simple program above. You
should find that it now runs without any security exceptions.
Table 10-2. ThreadGroup Class Methods That May Cause a Security Check
Defining your own permission and using it in a program is beyond the scope of this topic, but we
wanted to point out that you could do this if you really wanted to. For more information on how to
do this, as well as other security-related topics, read the Java 2 security documentation.
1. The garbage collector thread and the finalize() method
A common problem we have seen is when the garbage collector thread becomes deadlocked trying
to free up memory. Consider this situation: You have a legacy C-code application that is not
thread-safe and you want to call into the C functions from a Java program. This scenario is not all
that uncommon. An easy solution would have you synchronize methods that would access the C
functions. Defining the methods as synchronized would allow only one Java thread to access the C
functions at any given time. This seems like a logical assumption; however, since you are calling
into C code, you may also want to define a finalize() method to do some cleanup in the C
functions [i.e., calling free() to clean up memory used by the C code].
The problem that can result from a situation like this is a system deadlock. The reason why this
can happen is rather simple. Since access to all the non-thread-safe C functions is controlled via
synchronized Java methods, only one Java thread can access the C code at any given time. If an
object that was using these Java methods goes out of scope, it is eligible for garbage collection.
This makes sense, of course; however, when the finalize() method is called in the Java class,
it will try to call into the C code to perform some cleanup tasks. If a Java thread is already in one
of the C functions at the time of garbage collection, the entire system will hang. Why? Well when
the garbage collection thread kicks in (begins garbage collection), it suspends all the other threads
running in the Java VM. Now when the garbage collection thread calls into the finalize()
method, it will block waiting for access to the C code. Since the garbage collection thread has
suspended all other threads, the thread that is in the C code at the time of garbage collection will
Search WWH :