Interacting with a Java monitor from native code
So far, we have been synchronizing access to shared resources in Java threads using synchronized statements or synchronized methods:
synchronized (obj) { ... // synchronized block } synchronized void incrementCount() { ... // synchronized methods }
When we are executing a native method and want to have access to a resource or variable shared between multiple Java code and native code, the JNI offers us MonitorEnter
and MonitorExit
methods to control access to the mutual exclusion zone managed by a Java synchronized
block:
jint MonitorEnter(JNIEnv *env, jobject obj); jint MonitorExit(JNIEnv *env, jobject obj);
MonitorEnter
, the function responsible for acquiring access to the Java monitor scope, might block when another native thread or Java thread is the owner of the monitor. When any thread acquires access to the block, JVM will make sure that no other thread enters the critical section apart from the current thread.
MonitorExit
is the function...