Java Reference
In-Depth Information
a global reference prevents the garbage collector from unloading the class, the
field and/or method IDs remains valid for subsequent use. Again, we emphasize
that it is important to call DeleteGlobalRef() when the global reference is
no longer needed.
22.12 Threads and synchronization in JNI
As we discussed in Chapter 8, Java is a multithreaded system. Therefore, native
methods can conceivably be called by multiple threads. As such, it is your respon-
sibility to be certain that native methods are thread safe. In some situations, you
may have special knowledge that there will always be only one thread of con-
trol calling a native method. For example, the Java method that calls a native
method might be synchronized. Or the native method itself can be declared to be
synchronized.
Without such special knowledge, you must ensure that native methods do not
modify sensitive global variables in unprotected ways. A few simple rules apply:
The JNI environment pointer is valid only in the current thread. It must not be passed
between threads or cached and used in multiple threads. The JVM always passes the
same environment pointer in consecutive invocations of a native method from the same
thread. However, different threads pass different interface pointers to native methods.
Local references are valid only in the current thread. They should not be passed
between threads. If different threads need references to the same Java object, use global
references.
Global variables in native code have no intrinsic thread safety. If multiple threads access
global variables, you must be very careful to protect such access.
Critical sections of native code can be protected much like critical sections of
Java code. In Java, an entire method may be declared to be synchronized
or, for finer-grained control, a critical block of code can be protected with the
synchronized() statement:
synchronized (some - obj) {
... // critical code
}
The JVM permits only one thread to enter the synchronized block at a time.
For native code, the analogous JNI functions are MonitorEnter() and
MonitorExit() , used as follows
jenv- > MonitorEnter (some - jobject);
... // critical code
jenv- > MonitorExit (some - jobject);
Another option is to use the Java wait() , notify() and notifyAll()
mechanisms. JNI does not provide functions to directly support these opera-
tions, but, since they are normal Java methods on java.lang.Object , they
Search WWH ::




Custom Search