Android JNI/NDK Programming Four: JNI reference types

Source: Internet
Author: User

I. JNI reference type

JNI supports three types of opaque reference:local references, global references, and weak global references, which we'll explore in a second.

Local references

Most JNI functions create localref, such as NewObject creates an instance and returns a localref that points to the instance. Localref is only valid in native method of this thread. One but native method returns, Localref will be released. This means that we cannot cache localref to improve efficiency, because once the native method returns, Localref will be freed up and cached.
We already know that most of the JNI functions create localref, such as Newobject,findclass, which correspond to the creation, we can have two ways to make Localref invalid:

    1. Native method returns, JAVAVM automatically releases localref;
    2. Active release with Deletelocalref.
      DELETELOCALREF is defined as follows:
    void        (*DeleteLocalRef)(JNIEnv*, jobject);

Deletelocalref Active Release Localref is meaningful, if our memory is particularly tense, and a local method has a lot of memory-intensive localref, this time, in the local method to release these localref in time to relieve the memory pressure.
Localref is only valid in the thread that created the object, so we cannot use shared localref in other threads.

Global References

Global references are similar to globals, and can be used in multiple native methods or in multiple threads. Additionally, Golbal references prevent GC reclamation. However, unlike the general C global variables, Golbal references must be created and freed manually by a specific function. The following is the definition of a related function:

    jobject     (*NewGlobalRef)(JNIEnv*, jobject);    void        (*DeleteGlobalRef)(JNIEnv*, jobject);

Examples of Use:

//1. First define a static variable to store the global reference to static Jclass stringclass = NULL ; //2. Get local reference Jclass localrefcls =  (*env)->findclass (Env," java/lang/string "); return NULL; /* exception thrown */} //3. Create a global reference using that local reference Stringclass = (*env)->newglobalref (env, LOCALREFCLS); //4. Release local references (*ENV)->deletelocalref (env, LOCALREFCLS) in a timely manner;      

The above is a common, simple code process to create a global reference, and after use, remember to release it, and then memory leaks because the global reference is blocking the GC.

Weak Global References

The so-called weak global reference is another version of the global reference, and since it is a global reference, it has the ability to share across multiple threads, and we can use it in different functions of a single thread. It's weak because it can't block the GC. We said that the global reference is very strong, it can only be released manually, the JVM virtual machine cannot automatically GC it, but weak global will be recycled by the garbage collector, which is why.
Weak Global ref is created and deleted with Newglobalweakref in Deleteglobalweakref, and the attributes used in multiple local method invocations and in multithreaded contexts are the same as globalref. The two functions are defined in jni.h as follows:

    jweak       (*NewWeakGlobalRef)(JNIEnv*, jobject);    void        (*DeleteWeakGlobalRef)(JNIEnv*, jweak);

We see a new type here: Jweak, it's actually jobject, it's just a name that doesn't matter:

typedef jobject         jweak;

Examples of usage:

Static JclassString= null; if (string == NULL) {Jclass Local_ String = (*env) ->findclass (env, Span class= "hljs-string" > "java/lang/string"); if (mycls2local == NULL) {return; /* can ' t find class */} string = newweakglobalref (env, local_string); if (myCls2 == null) { return; /* Out of Memory */}}           

Since the weak global reference may be recycled by the garbage collector, we must determine whether it is empty before using it. If it is empty, you need to recreate it and continue using it without being empty.

Two. Comparing Reference

Since we can have multiple references, it could be a global reference, a weak global reference, or a local reference, how do we tell if it is the same reference? Without a rush, JNI has provided us with a good function, which we can use directly, as defined below:

jboolean    (*IsSameObject)(JNIEnv*, jobject, jobject);

If connected, return Jni_true, otherwise return jni_false.

Three. Reference management

Reference management is used for less memory usage and improves code efficiency. The three types of citations supported by JNI have their own uses and must not be abused. The author level is limited, there is not much nonsense, here is mainly about the local reference management.
JNI provides a set of functions to manage local references:

    jint        (*PushLocalFrame)(JNIEnv*, jint);    jobject     (*PopLocalFrame)(JNIEnv*, jobject);

The

calls &NBSP when it enters the local method,
Pushlocalframe, and calls Poplocalframe at the end of the local method. This method is highly efficient, and it is recommended to use this approach.  
Make sure that the context exits only one, or that each return statement is strictly checked to see if the poplocalframe is called. Because forgetting to call Poplocalframe may cause the JVM to crash.  
Usage Example:

jobject hello(JNIEnv *env, jobject obj){jobject result;//进入函数后pushif ((*env)->PushLocalFrame(env, 10) < 0) {/* frame not pushed, no PopLocalFrame needed */return NULL;}...result = ...;if (...) {//认真检查每一个函数的出口,绝不能忘记PopLocalFrameresult = (*env)->PopLocalFrame(env, result);return result;}...//正常返回前pop一下result = (*env)->PopLocalFrame(env, result);return result;}

Android JNI/NDK Programming Four: JNI reference types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.