The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Java Native Interface
Lesson: Interacting with Java from the Native Side

Threads and Native Methods

The 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. Doing Two or More Tasks At Once: Threads(in the Java Native Interface trail)covers programming with threads. In particular, the page Synchronizing Threads(in the Java Native Interface trail)covers issues related to writing programs that contain multiple threads, including how to synchronize them.

Threads and JNI

Thread Synchronization in Native Methods

The JNI provides two synchronization functions that allow you to implement synchronized blocks. In Java, you implement synchronized blocks using the synchronized statement. For example:
synchronized (obj) {
    ...                   /* synchronized block */
    ...
}

The Java Virtual Machine guarantees that a thread must acquire the monitor associated with a Java object obj before it can execute the statements in the block. Therefore, at any given time, there can be at most one thread running inside the synchronized block.

Native code can perform equivalent synchronization on objects using the JNI functions MonitorEnter and MonitorExit. For example:

...
(*env)->MonitorEnter(env, obj);
...                      /* synchronized block */
(*env)->MonitorExit(env, obj);
...
A thread must enter the monitor associated with 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 Notify

The functions Object.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.
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form