JNI programming pitfalls fall into two categories:, the IDs returned for a given class don't change for the lifetime of the JVM process.But the call to get the field or method can require significant work in the JVM, because fields and methods might have been inherited from superclasses, making the JVM walk up the class hierarchy to find them.For example, the JVM might return a copy when it has optimized arrays in a way that does not store them contiguously.These calls, then, might cause copying of the elements being manipulated.It provides a clean separation between the execution of Java code and native code (such as C/C ) by defining a clear API for communicating between the two.For the most part, it avoids direct memory reference by native code into the JVM, ensuring that natives can be written once and work across different JVM implementations or versions.Because the IDs are the same for a given class, you should look them up once and then reuse them.
Caching makes a significant impact on your application's run time.
To maintain this separation, arrays are passed as opaque handles, and native code must call back to the JVM in order to manipulate array elements using set and get calls.
The Java specification leaves it up to the JVM implementation whether these calls provide direct access to the arrays or return a copy of the array.
The goal is to help you recognize and steer clear of them so that you can write safe, effective JNI code that performs well from the start.
This article also introduces available tools and techniques for finding these issues in new or existing code and show how to apply them effectively.