Java Reference
In-Depth Information
to Java garbage collection, or by “pinning” the actual Java array elements in mem-
ory. The choice to copy or pin is completely up to the JVM; the programmer has no
control over which method is used. If pinned, then calling
ReleaseFloatAr-
rayElements()
is important in order to unpin the array elements in memory
so that future runs of the garbage collector are able to move the array as needed.
If copied, then calling
ReleaseFloatArrayElements()
is important in
order to copy the changed array back to the Java side and avoid a memory
leak. In other words,
always
be sure to call the corresponding
ReleaseXxxAr-
rayElements()
function after using one of the
GetXxxArrayElements()
functions.
The careful reader may have noticed that we passed
NULL
as the second param-
eter to both
GetStringUTFChars()
and
GetFloatArrayElements()
.
That parameter may optionally be a
jboolean
type. Upon return from the
array functions, the
jboolean
,ifpresent, is set to
JNI
-
TRUE
if a copy of
the actual Java array elements is returned and
JNI
-
FALSE
if a pointer to the
actual elements themselves is returned - i.e. if the array is pinned in memory. If
JNI
-
FALSE
, then changes made to array elements appear instantly on the Java
side. If
JNI
-
TRUE
, then any changes to the array do not appear on the Java side
until
ReleaseFloatArrayElements()
is called. The same concept applies
to the string functions as well, although a copy is almost always made for strings
since the native platform is unlikely to have direct support for Java's Unicode
character format.
When calling
ReleaseFloatArrayElements()
from C
, there is a
jint
“mode” parameter in the third argument position. The mode may be 0,
as in the example above, or one of the constants
JNI
-
COMMIT
or
JNI
-
ABORT
.
Mode 0, almost always the proper choice, means to copy back the content, if
necessary, and release or unpin the memory for the
c
-
array
.
JNI
-
COMMIT
means to copy the content but not release the memory, and
JNI
-
ABORT
means
to free the buffer without copying back the possible changes. Both these special
values should be used with great care, if at all.
++
22.6.1 Handling subsets of arrays with
Get
and
Set
region functions
In practice, getting an entire array with one of the
GetXxxArrayElements()
functions can be expensive, especially if a copy is made (and that choice is out of
the developer's hands). If only a subset of an array is needed, then JNI provides
GetXxxArrayRegion()
methods, with
“
Xxx
„
replaced with
Float
,
Int
,
Double
, etc. Suppose we have a Java
int[]
array that is 1000 elements long.
It becomes a
jintArray
on the C side. If we only need to access elements 5 to
14, we can get access to that subset of the large array as follows:
jint region[10];
jenv-
>
GetIntArrayRegion (the
-
jarray, 5, 10, region);
Search WWH ::
Custom Search