From 868d74eb3fa7f6ca7a75002788516c4c37bb6f0a Mon Sep 17 00:00:00 2001 From: Elliott Hughes Date: Tue, 27 Sep 2011 16:27:31 -0700 Subject: [PATCH] Add ICS-specific notes to the JNI tips documentation. Change-Id: I9be8f2452063363d9f2b6c28b5a2eacac09308a1 --- docs/html/guide/practices/design/jni.jd | 168 +++++++++++++----------- 1 file changed, 89 insertions(+), 79 deletions(-) diff --git a/docs/html/guide/practices/design/jni.jd b/docs/html/guide/practices/design/jni.jd index 6e984b00a8811..9980efdf0c3f4 100644 --- a/docs/html/guide/practices/design/jni.jd +++ b/docs/html/guide/practices/design/jni.jd @@ -26,9 +26,9 @@ page.title=JNI Tips -

JNI is the Java Native Interface. It defines a way for code written in the -Java programming language to interact with native -code: functions written in C/C++. It's VM-neutral, has support for loading code from +

JNI is the Java Native Interface. It defines a way for managed code +(written in the Java programming language) to interact with native +code (written in C/C++). It's vendor-neutral, has support for loading code from dynamic shared libraries, and while cumbersome at times is reasonably efficient.

You really should read through the @@ -46,13 +46,13 @@ There's a more detailed +which allow you to create and destroy a JavaVM. In theory you can have multiple JavaVMs per process, +but Android only allows one.

The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as the first argument.

-

On some VMs, the JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads. +

The JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads. If a piece of code has no other way to get its JNIEnv, you should share the JavaVM, and use GetEnv to discover the thread's JNIEnv. (Assuming it has one; see AttachCurrentThread below.)

@@ -66,23 +66,22 @@ that header refers to JNIEnv.)

Threads

-

All VM threads are Linux threads, scheduled by the kernel. They're usually -started using Java language features (notably Thread.start), -but they can also be created elsewhere and then attached to the VM. For +

All threads are Linux threads, scheduled by the kernel. They're usually +started from managed code (using Thread.start), +but they can also be created elsewhere and then attached to the JavaVM. For example, a thread started with pthread_create can be attached with the JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is -attached to the VM, it has no JNIEnv, and -cannot make JNI calls.

+attached, it has no JNIEnv, and cannot make JNI calls.

-

Attaching a natively-created thread causes the VM to allocate and initialize -a Thread object, add it to the "main" ThreadGroup, -and add the thread to the set that is visible to the debugger. Calling -AttachCurrentThread on an already-attached thread is a no-op.

+

Attaching a natively-created thread causes a java.lang.Thread +object to be constructed and added to the "main" ThreadGroup, +making it visible to the debugger. Calling AttachCurrentThread +on an already-attached thread is a no-op.

-

The Dalvik VM does not suspend threads executing native code. If +

Android does not suspend threads executing native code. If garbage collection is in progress, or the debugger has issued a suspend -request, the VM will pause the thread the next time it makes a JNI call.

+request, Android will pause the thread the next time it makes a JNI call.

Threads attached through JNI must call DetachCurrentThread before they exit. @@ -108,12 +107,12 @@ the argument.)

Similarly, to call a method, you'd first get a class object reference and then a method ID. The IDs are often just -pointers to internal VM data structures. Looking them up may require several string +pointers to internal runtime data structures. Looking them up may require several string comparisons, but once you have them the actual call to get the field or invoke the method is very quick.

If performance is important, it's useful to look the values up once and cache the results -in your native code. Because there is a limit of one VM per process, it's reasonable +in your native code. Because there is a limit of one JavaVM per process, it's reasonable to store this data in a static local structure.

The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded. Classes @@ -145,13 +144,17 @@ then reloaded, it will be executed again.

Local and Global References

-

Every object that JNI returns is a "local reference". This means that it's valid for the +

Every argument passed to a native method, and almost every object returned +by a JNI function is a "local reference". This means that it's valid for the duration of the current native method in the current thread. -Even if the object itself continues to live on after the native method returns, the reference is not valid. -This applies to all sub-classes of jobject, including +Even if the object itself continues to live on after the native method +returns, the reference is not valid. +

This applies to all sub-classes of jobject, including jclass, jstring, and jarray. -(Dalvik VM will warn you about most reference mis-uses when extended JNI +(The runtime will warn you about most reference mis-uses when extended JNI checks are enabled.)

+

The only way to get non-local references is via the functions +NewGlobalRef and NewWeakGlobalRef.

If you want to hold on to a reference for a longer period, you must use a "global" reference. The NewGlobalRef function takes the @@ -159,7 +162,7 @@ local reference as an argument and returns a global one. The global reference is guaranteed to be valid until you call DeleteGlobalRef.

-

This pattern is commonly used when caching copies of class objects obtained +

This pattern is commonly used when caching a jclass returned from FindClass, e.g.:

jclass localClass = env->FindClass("MyClass");
 jclass globalClass = reinterpret_cast<jclass>(env->NewGlobalRef(localClass));
@@ -181,22 +184,25 @@ not use jobject values as keys.

Programmers are required to "not excessively allocate" local references. In practical terms this means that if you're creating large numbers of local references, perhaps while running through an array of -Objects, you should free them manually with +objects, you should free them manually with DeleteLocalRef instead of letting JNI do it for you. The -VM is only required to reserve slots for +implementation is only required to reserve slots for 16 local references, so if you need more than that you should either delete as you go or use -EnsureLocalCapacity to reserve more.

+EnsureLocalCapacity/PushLocalFrame to reserve more.

-

Note that jfieldIDs and jmethodIDs are just integers, not object -references, and should not be passed to NewGlobalRef. The raw data +

Note that jfieldIDs and jmethodIDs are opaque +types, not object references, and should not be passed to +NewGlobalRef. The raw data pointers returned by functions like GetStringUTFChars -and GetByteArrayElements are also not objects.

+and GetByteArrayElements are also not objects. (They may be passed +between threads, and are valid until the matching Release call.)

One unusual case deserves separate mention. If you attach a native -thread to the VM with AttachCurrentThread, the code you are running will -never "return" to the VM until the thread detaches from the VM. Any local -references you create will have to be deleted manually unless you're going -to detach the thread soon.

+thread with AttachCurrentThread, the code you are running will +never automatically free local references until the thread detaches. Any local +references you create will have to be deleted manually. In general, any native +code that creates local references in a loop probably needs to do some manual +deletion.

UTF-8 and UTF-16 Strings

@@ -205,14 +211,15 @@ to detach the thread soon.

modified encoding is useful for C code because it encodes \u0000 as 0xc0 0x80 instead of 0x00. The nice thing about this is that you can count on having C-style zero-terminated strings, suitable for use with standard libc string functions. The down side is that you cannot pass -arbitrary UTF-8 data into the VM and expect it to work correctly.

+arbitrary UTF-8 data to JNI and expect it to work correctly.

-

It's usually best to operate with UTF-16 strings. With Android's current VMs, the -GetStringChars method -does not require a copy, whereas GetStringUTFChars requires a malloc and a UTF conversion. Note that +

If possible, it's usually faster to operate with UTF-16 strings. Android +currently does not require a copy in GetStringChars, whereas +GetStringUTFChars requires an allocation and a conversion to +UTF-8. Note that UTF-16 strings are not zero-terminated, and \u0000 is allowed, so you need to hang on to the string length as well as -the string pointer.

+the jchar pointer.

Don't forget to Release the strings you Get. The string functions return jchar* or jbyte*, which @@ -237,9 +244,8 @@ While arrays of objects must be accessed one entry at a time, arrays of primitives can be read and written directly as if they were declared in C.

To make the interface as efficient as possible without constraining -the VM implementation, -the Get<PrimitiveType>ArrayElements family of calls -allows the VM to either return a pointer to the actual elements, or +the VM implementation, the Get<PrimitiveType>ArrayElements +family of calls allows the runtime to either return a pointer to the actual elements, or allocate some memory and make a copy. Either way, the raw pointer returned is guaranteed to be valid until the corresponding Release call is issued (which implies that, if the data wasn't copied, the array object @@ -253,7 +259,7 @@ non-NULL pointer for the isCopy argument. This is rarely useful.

The Release call takes a mode argument that can -have one of three values. The actions performed by the VM depend upon +have one of three values. The actions performed by the runtime depend upon whether it returned a pointer to the actual data or a copy of it: