I’ve recently started targeting API level 14 with my Android JNI application, and immediately discovered problems described here.
Failing to solve the problem by explicitly managing local references (got local ref table overflow in the end of my experiments), I’ve decided to simply switch to global refs. Now I’m getting “attempt to use stale global reference” problem that isn’t described in that article.
Here’s what I’m trying to do: there’s a single object that has a container of jobjects. Whenever Java calls my native method and passes a reference I need to store for later use, I create new global ref to that jobject, add global ref to the container and also store its index. Whenever I need to use the jobject I get it by index. What is the problem with this approach?
P. S. Whenever I call JNI methods, I am using correct JNIEnv for the calling thread. The thread making JNI calls is attached to JVM.
I smell deeper problems in your code. Local ref table overflow simply cannot happen if you are aware of all local refs you are creating and deleting them properly, manually, earlier than returning from the current JNI call. The local ref creation might be very subtle, it’s not just
FindClass.Anyway, if you want to make it working with global refs (which seems like the right thing to do anyway, given the usage scenario you described) i suspect this: your “container” needs those stored refs to be also removed sometimes, not just added i guess. Are you sure that you are removing the right ones, and calling
DeleteGlobalRefon the right ones, not some others which stay in the container? Put it another way, for eachNewGlobalRefyou have in your code, make sure that you know where is the relevantDeleteGlobalRefand that you are confident about when and why it’s being called.