JNI reference and Cache

Source: Internet
Author: User

Global Reference/local reference/weak global reference

Passing the object created from the Java Virtual Machine to the local C/C ++ code will produce reference. Based on the Java garbage collection mechanism, Java object garbage collection will not be triggered if a reference exists.
These references are divided into three types in JNI:
1. Global Reference)
2. Local reference)
3. weak global reference)
---------------------------------------
1. Local references (commonly used) are basically local references returned by JNI.
For example, newobject returns the local reference of the created instance. Local applications are only valid in the native function. All local references generated in this function will be automatically released (freed) when the function returns. You can also use the deletelocalref function to automatically release this reference.
In the validity period of a local reference, it can be passed to other functions. It should be emphasized that its validity period is still only in one Java local function call, therefore, you must never use the C ++ global variable to save it or define it as a C ++ static local variable.
2. Global Reference
Global references can span the current thread and are valid in multiple native functions. However, programmers need to manually release the reference to prevent garbage collection during the existence of global references.
Unlike local references, global references cannot be created automatically by JNI. Global references call the newglobealref function, while releaseglobalref is used to release global references.
3. weak global reference
Functions provided by Java are similar to global references. Creation and deletion must be performed by programmers. Similar to global references, such references can be effective in multiple local codes and across multiple threads, however, this reference will not prevent the garbage collector from recycling the object pointed to by this reference.
Use newweakglobalref and releaseweakglobalref to generate and release references.
Some referenced functions:
Jobject newglobalref (jobject OBJ); // create a global reference
Jobject newlocalref (jobject OBJ); // create a local reference
Jobject newweakglobalref (jobject OBJ); // creates a weak global reference.
Void deleteglobalref (jobject OBJ); // deletes a global reference.
Void deletelocalref (jobject OBJ); // deletes a local reference.
Void deleteweakglobalref (jobject OBJ); // deletes a weak global reference.
Jboolean issameobject (jobject obj1, jobject obj2); // determines whether two references point to the same Java object
This function has a special function for weak global references. If null is passed into the object to be compared, you can determine whether the Java object pointed to by the weak global reference is recycled.
----------------------------------------------------------------------
Cache:
Cache jfieldid/jmethodid
When jfieldid and jmethodid are obtained, the corresponding jfieldid/jmethodid will be queried by adding a signature to the property/method name. This kind of query has a large overhead, so we can cache these fieldid/methodid, in this way, you only need to query once and then use the cached fieldid/methodid.
Cache method:
1. cache (caching at the point of use)
2. Cache during Java class initialization (caching at The Defining class's inititalizer)
----------------
Cache for the first time:
Use static local variables in native code to save the queried IDs, so that they will not be queried during each function call, but will be saved after the first query is successful.
Example: jniexport void jnicall java_test_native (jnienv * ENV, jobject OBJ)
{
Static jfieldid fieldid_string = NULL;
Jclass clazz = env-> getobjectclass (OBJ );
If (fieldid_string = NULL)
{
Fieldid_string = env-> getfieldid (class, "string", "ljava/lang/string ;");
}
.......................
}
---------------
Cache during Java class initialization
A better way is to store all the ids before any native function call. We can let Java call the local code to initialize all jfieldid/jmethodid when loading this type for the first time. In this way, we can save multiple statements to determine whether the ID exists. Of course, these jfieldid/jmethodid are defined globally in C/C ++.
This method also has advantages. When the Java class is uninstalled or reloaded, the local code will be re-called to re-calculate IDs.
Example: Java class:

public class TestNative{   static{ initNativeIDs();}   static native void initNativeIDs();   int propInt=0;   String propStr="";   public native void otherNative();   public static void main(String[] args) {}}

 

C/C ++ code:

Jfieldid region = 0; jfieldid g_propstr_id = 0; jniexport void region (jnienv * ENV, jobject clazz) {g_propint_id = getfieldid (clazz, "propint", "I "); g_propstr_id = getfieldid (clazz, "propstr", "ljava/lang/string;");} jniexport void jnicalljava_testnative_othernative (jnienv * ENV, jobject OBJ) {// you can directly use the values of g_propint_id and g_propstr_id}

 

------------------------------------------------
Two disadvantages of using JNI
1. If JNI is used, this Java application cannot be cross-platform. If it is to be transplanted to other platforms, native code needs to be rewritten.
2. Java is a strongly typed language, but C/C ++ is not. Therefore, you must be more careful when writing JNI.
In short, you must use as little local code as possible when building a Java program.

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.