should expect). However, given that native code (outside the system classes) is usually used for
speed or to access system-specific APIs, there is usually little need to do this.
Example 10-4 Locking Monitors from C Code
// Critical Section
Native methods can also use native synchronization objects to coordinate their actions with other
native threads. All of this will operate correctly with Java.
Threads originally created outside Java can attach to the JVM using JNI
[AttachCurrentThread()]. Once a thread is attached to the JVM, it will receive a Java
wrapper and appear to the JVM as a normal Java thread, including being entered into a thread
group. It will be able to access Java objects and invoke methods on them, including the usual
synchronization methods. Any thread, whether originally Java or native, can create additional
native threads in the native method. However, any such thread must attach itself to the JVM
before it can interact with any Java objects. A native thread that calls in to the JVM can also create
and start Java threads.
In Figure 10-1 you can see the basic Java threading design when using the native thread libraries.
The Java thread objects are built by and controlled by the JVM, but the threads themselves are
actually native threads that are created and controlled by the native library. The actual context
switching, locking, etc., are done by the native threads library, which is why things work together.
Figure 10-1. Java Thread Objects Use Native Threads
Within native code all exceptions are synchronous, including those caused by stop().
Exceptions are detected either by explicit polling using ExceptionOccurred() or in some
cases by checking return values. Once an exception is raised it must be dealt with (by clearing or
by returning and thus propagating to Java code). It is not safe to call further JNI methods (other
than those for dealing with exceptions) until the exception has been dealt with.
You cannot share local Java objects from one native thread to another, nor should you hold on to
references across multiple JNI calls to C code, even from the same thread. Java will pass C an
interface pointer (JNIEnv *) which is valid only for that thread on that call. If you wish to share
Search WWH :