Saturday, April 20, 2013

jni jnienv DeleteGlobalRef example c c++ java


DeleteGlobalRef


void DeleteGlobalRef(JNIEnv *env, jobject globalRef);

Deletes the global reference pointed to by globalRef.
LINKAGE:
Index 22 in the JNIEnv interface function table.
PARAMETERS of DeleteGlobalRef

env: the JNI interface pointer.

globalRef: a global reference.

Local References

Local references are valid for the duration of a native method call. They are freed automatically after the native method returns. Each local reference costs some amount of Java Virtual Machine resource. Programmers need to make sure that native methods do not excessively allocate local references. Although local references are automatically freed after the native method returns to Java, excessive allocation of local references may cause the VM to run out of memory during the execution of a native method.
Example - DeleteGlobalRef 
static jobject myObjGlobalRef;
static JNIEnv* env = /* call to create a JVM and get the JNI env */;
jobject ReturnMyObj()
{
    /* <<Code that defines class, constructorId, and param1 goes here>> */

    jobject localObj = env->NewObject(class, constructorId, param1);
    myObjGlobalRef = env->NewGlobalRef(localObj);
}

void DeleteMyObj()
{
    env->DeleteGlobalRef(myObjGlobalRef);
}

myObjGlobalRef = ReturnMyObj();

jobject otherExistingGlobalRef = /* Assume we get another global ref to another parent obj somewhere else */
/*  ... other code here ... */
// Invoke some method on some other pre-existing global reference that uses
// myObjGlobalRef,  lets assume this method stores the object referenced by
// myObjGlobalRef into a parent object referenced by otherExistingGlobalRef:
env->CallVoidMethod(env, otherExistingGlobalRef, addASubObjectMethodId, myObjGlobalRef);

DeleteMyObj();