Wednesday, April 24, 2013

jni jnienv MonitorEnter example c c++ java


MonitorEnter


jint MonitorEnter(JNIEnv *env, jobject obj);

Enters the monitor associated with the underlying Java object referred to by obj.
Enters the monitor associated with the object referred to by obj. The obj reference must not be NULL.(MonitorEnter)
Each Java object has a monitor associated with it. If the current thread already owns the monitor associated with obj, it increments a counter in the monitor indicating the number of times this thread has entered the monitor. If the monitor associated with obj is not owned by any thread, the current thread becomes the owner of the monitor, setting the entry count of this monitor to 1. If another thread already owns the monitor associated with obj, the current thread waits until the monitor is released, then tries again to gain ownership.
A monitor entered through a MonitorEnter JNI function call cannot be exited using the monitorexit Java virtual machine instruction or a synchronized method return. A MonitorEnter JNI function call and a monitorenter Java virtual machine instruction may race to enter the monitor associated with the same object.
To avoid deadlocks, a monitor entered through a MonitorEnter JNI function call must be exited using the MonitorExit JNI call, unless the DetachCurrentThread call is used to implicitly release JNI monitors.
LINKAGE:
Index 217 in the JNIEnv interface function table.
PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.
Example of MonitorEnter
JNIEXPORT void JNICALL Java_company_com_HelloActivity_setBuffer(JNIEnv *env, jobject obj, jstring jstr)
{
    char buf[256];

    int len = (*env)->GetStringLength(env, jstr);       
    (*env)->GetStringUTFRegion(env, jstr, 0, len, buf);
    (*env)->MonitorEnter(env, obj); // I don't think this is correct.
    strcat(buffer, buf); // buffer is declared as global char buffer[256];
    (*env)->MonitorExit(env, obj);
}
EDIT: How about this? syncobj is defined in Activity as static Object and shared with another thread.
JNIEXPORT void JNICALL Java_company_com_HelloActivity_setBuffer(JNIEnv *env, jobject obj, jstring jstr, jobject syncobj)
{
    char buf[256];

    int len = (*env)->GetStringLength(env, jstr);       
    (*env)->GetStringUTFRegion(env, jstr, 0, len, buf);
    (*env)->MonitorEnter(env, syncobj);
    strcat(buffer, buf);
    (*env)->MonitorExit(env, syncobj);
}