MonitorExit
jint MonitorExit(JNIEnv *env, jobject obj);
The current thread must be the owner of the monitor associated with the underlying Java object referred to by
obj
.(MonitorExit) The thread decrements the counter indicating the number of times it has entered this monitor. If the value of the counter becomes zero, the current thread releases the monitor.
Native code must not use
MonitorExit
to exit a monitor entered through a synchronized method or a monitorenter
Java virtual machine instruction.LINKAGE:
Index 218 in the JNIEnv interface function table.PARAMETERS of MonitorExit
env
: the JNI interface pointer.obj
: a normal Java object or class object.RETURNS of MonitorExit
Returns “0” on success; returns a negative value on failure.
EXCEPTIONS:
IllegalMonitorStateException
: if the current thread does not own the monitor.
Example of MonitorExit
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);
}