|
|
|
|||
|
Threads and Native MethodsThe Java platform is a multithreaded system. Because of this, native methods must be thread-safe programs. Unless you have knowledge to the contrary, such as knowing that the native method is synchronized, you must assume that there can be multiple threads of control executing a native method at any given time. Native methods therefore must not modify sensitive global variables in unprotected ways. That is, they must share and coordinate their access to variables in certain critical sections of code. Before reading this section, you should be familiar with the
concepts of threads of control and multithreaded programming.
Threads of Control Threads and JNI
Thread Synchronization in Native MethodsThe JNI provides two synchronization functions that allow you to implement synchronized blocks. In Java, you implement synchronized blocks using thesynchronized statement. For example:
The Java Virtual Machine guarantees that a thread must acquire the
monitor associated with a Java object Native code can perform equivalent synchronization on objects using the
JNI functions A thread must enter the monitor associated with... (*env)->MonitorEnter(env, obj); ... /* synchronized block */ (*env)->MonitorExit(env, obj); ... obj
before it can continue its execution. A thread is allowed to enter a
monitor multiple times. The monitor contains a counter signaling how
many times it has been entered by a given thread. MonitorEnter
increments the counter when the thread enters a monitor it has already
entered. MonitorExit decrements the counter.
Other threads can enter the monitor when the counter reaches zero (0).
Wait and NotifyThe functionsObject.wait,
Object.notify, and Object.notifyAll provide another useful thread synchronization mechanism. While the JNI
does not directly support these functions, a native method
can always follow the JNI method call
mechanism to invoke them.
| |||
|