简体   繁体   中英

Android JNI Global Reference Subtleties

Ok so given the following steps taken from Cpp

  • Use jni to make a dictionary
  • Make the jobject of the dictionary returned into a globalref
  • Use jni to call a Java method that returns an object (we will call this object *A*)
  • Add *A* to the dictionary WITHOUT making the ref of *A* global

What is the lifespan of the *A* ?

My expectations are as follows. The dictionary itself is global and so is protected from garbage collection, when I call the 'Add' method from jni *A* is passed 'back into java' and then the dictionary will hold a new reference to it, protecting it too from garbage collection. So I expect *A* to last as long as the dictionary (ignoring outside meddling).

Am I on the right track here? Thanks.

when I call the 'Add' method from jni A is passed 'back into java' and then the dictionary will hold a new reference to it, protecting it too from garbage collection.

No. You are conflating two properties of local and global references. A local reference is only valid for the duration of the JNI call it is created in. After that, it's invalid. If you want to use it again in a subsequent JNI call, make it a GlobalRef.

So I expect A to last as long as the dictionary (ignoring outside meddling).

Yes, but the reference itself has become invalid so you can't use it anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM