开发者

JNI object references obtained through the Invocation API: local or global?

I'm using the JNI invocation API, which starts a JVM within a C program; in this situation, you get a JNIEnv pointer which remains valid until you explicitly destroy the JVM. Does the local/global distinction still apply here? What's the meaning of a local reference to a开发者_开发百科 newly created object, since the JNIEnv remains in scope all the time?


The JNI book is a little terse about this situation, but you can figure it out if you study it long enough. Basically, when you attach a native C thread to the JVM, you create a local context which can store some local references.

These local references will never be freed until you manually free them with DeleteLocalRef, or you destroy the local context by calling DetachThread. Since you're probably not doing a lot of attaching and detaching to JVMs, it's very important for you to call DeleteLocalRef on every local reference you create.

The natural next question is "why create global refs at all, if local refs don't get GC'ed until the JVM is detached?" Well, local references cannot be shared between threads. So you still have to create global references to do that.


I think the thread which created JVM becomes Java thread, which, like any thread created in Java, or attached via AttachCurrentThread(), has its local stack frame. So any object you create, becomes a local reference in this stack frame, which will expire when you destroy JVM (you can't detach main thread), or call DeleteLocalRef().


Presumably a call DettachCurrentThread() releases the references as well. Unfortunately the JNI spec does not clearly define the behavior of references for the invocation API, and it may be that the actual semantics may depend on the specific JVM implementation :S

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜