If JNI DeleteGlobalRef () is called, is the corresponding java object garbage collected?

What I mean if I create a global reference jobject in C ++ and then pipe that to some Java code and delete the call to DeleteGlobalRef () is the fact that an explicit object, potentially garbage collected immediately, so any future Java code that already referencing this object can return with NullPointerException? In particular, if I have some C ++ code that does something like this simplified example:

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();

// Does the pointed to by myObjGlobalRef still exist here, assuming that
// otherExistingGlobalRef now references it?

      

How does it work in JNI? Is the "GlobalReference" for an object only a reference to the object, so that if I free the GlobalReference object, it does not necessarily garbage collect the underlying Java object as long as all references to it (such as the "parent" otherExistingGlobalRef object referencing it ) gone?

If you can answer this question and provide a link to some official Java / Sun / Oracle documentation backing up your answer, then you get bonus rewards :-).

+10


source to share


1 answer


DeleteGlobalRef () releases the reference, not the object.

If this was the last available link, then the referenced object is available for garbage collection.

Whether "GlobalReference" for an object is just an object reference



Not. It is simply a link that remains valid until you explicitly release it. Java garbage collection is independent of references at all.

See also Oracle documentation on global links .

+11


source







All Articles