Tomasz Kryński
Tomasz Kryński

Reputation: 541

JNI LocalRef from WeakGlobalRef

I had issue that WeakGlobalRef pointed to garbage collected object, this crashed application when I try to call CallVoidMethod on this ref. To fix this I do following:

jobject javaObject = pEnv->NewLocalRef(m_pJavaObject);

if (javaObject)
{
    pEnv->CallVoidMethod(javaObject, method, object);
}

This still crashing at CallVoidMethod, is this valid to do it like that or should I also do check on local ref IsSameObject

Last thing I get on dump, higher nothing that can point any method:

Crash reason:  SIGSEGV
Crash address: 0xdead4321
Process uptime: not available

Thread 0 (crashed)
(...)
41  libart.so + 0xba7df
     sp = 0xbeed2dc0    pc = 0xb4eca7e1
    Found by: stack scanning
42  libxxx.so!_JNIEnv::CallVoidMethod(_jobject*, _jmethodID*, ...) [jni.h : 650 + 0x1]
     sp = 0xbeed2dd8    pc = 0x9fabbeb9
    Found by: stack scanning

Upvotes: 1

Views: 673

Answers (1)

Michael
Michael

Reputation: 58467

should I also do check on local ref IsSameObject

The documentation provides the answer:

it is recommended that a standard (strong) local or global reference to the same object be acquired using the JNI functions NewLocalRef or NewGlobalRef, and that this strong reference be used to access the intended object. These functions will return NULL if the object has been freed, and otherwise will return a strong reference (which will prevent the object from being freed). The new reference should be explicitly deleted when immediate access to the object is no longer required, allowing the object to be freed.

If the object has been freed you would get NULL from NewLocalRef, hence there is no need to call IsSameObject.

Upvotes: 1

Related Questions