JNI reference says that
"Local references are valid for the duration of a native method call. They are freed automatically after the native method returns.
Source: http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html#global_local
I'm kind of lost here. According to above, I must explicitly call NewGlobalRef and pass object returned from a call to NewObject.
I tried this and it seems that when a GC kicks in, it does not collect my references (like something still holds onto them).
Consider the following project:
Main.java:
package lv.example;
import java.io.IOException;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Object> store = new ArrayList<Object>();
while(true) {
Object d = null;
try {
int c = System.in.read();
d = Dummy.getWeakGlobalRef();
if(c == 'c')
store.clear();
store.add(d);
System.out.println(d);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Dummy.java:
package lv.example;
class Dummy {
static {
System.loadLibrary("dummy");
}
native static Dummy getLocalRef();
native static Dummy getGlobalRef();
native static Dummy getWeakGlobalRef();
@Override
protected void finalize() throws Throwable {
System.out.println("Finalized");
}
}
libdummy.so contains implementation of native methods:
JNIEXPORT jobject JNICALL Java_lv_example_Dummy_getLocalRef (JNIEnv *env, jclass cls) {
jmethodID id = env->GetMethodID(cls, "<init>", "()V");
return env->NewObject(cls, id);
}
JNIEXPORT jobject JNICALL Java_lv_example_Dummy_getGlobalRef (JNIEnv *env, jclass cls) {
jmethodID id = env->GetMethodID(cls, "<init>", "()V");
return env->NewGlobalRef(env->NewObject(cls, id));
}
JNIEXPORT jobject JNICALL Java_lv_example_Dummy_getWeakGlobalRef (JNIEnv *env, jclass cls) {
jmethodID id = env->GetMethodID(cls, "<init>", "()V");
return env->NewWeakGlobalRef(env->NewObject(cls, id));
}
Behaviour that main loop exhibits seems strange to me:
1) When I call getWeakGlobalRef or getLocalRef and clear ArrayList, GC seems to collect all the Dummy objects I've created.
2) When I call getGlobalRef, no objects get collected regardless if I clear ArrayList or not.l
I'm kind of confused here, does that mean that I can return local references from native methods back to Java code?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…