1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   2     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   3 <html lang="en-US" xmlns="http://www.w3.org/1999/xhtml" xml:lang=
   4 "en">
   5 <head>
   6 <title>Design Overview</title>
   7 <link rel="Table of Contents" href="jniTOC.html" />
   8 <link rel="Previous" href="intro.html" />
   9 <link rel="Next" href="types.html" />
  10 <link rel="Index" href="backcover.html" />
  11 </head>
  12 <body>
  13 <a href="#skip" title="Skip navigation bar"></a>
  14 
  15 <table width="100%" summary="">
  16 <tr>
  17 <td><a accesskey="c" href="jniTOC.html">Contents</a> |
  18 <a accesskey="p" href="intro.html">Previous</a> | <a accesskey="n"
  19 href="types.html">Next</a></td>
  20 </tr>
  21 </table>
  22 <a name="skip" id="skip"></a> 
  23 <h1>Chapter 2: Design Overview</h1>
  24 
  25 <p>This chapter focuses on major design issues in the
  26 JNI. Most design issues in this section are related to native
  27 methods. The design of the Invocation API is covered in <a href=
  28 "invocation.html">Chapter 5: The Invocation API</a>.</p>
  29 
  30 <p>This chapter covers the following topics:</p>
  31 
  32 <ul>
  33   <li><a href="#jni_interface_functions_and_pointers">JNI Interface Functions and Pointers</a></li>
  34   <li><a href="#compiling_loading_and_linking_native_methods">Compiling, Loading and Linking Native Methods</a>
  35     <ul>
  36       <li><a href="#resolving_native_method_names">Resolving Native Method Names</a></li>
  37       <li><a href="#native_method_arguments">Native Method Arguments</a></li>
  38     </ul>
  39   </li>
  40   <li><a href="#referencing_java_objects">Referencing Java Objects</a>
  41     <ul>
  42       <li><a href="#global_and_local_references">Global and Local References</a></li>
  43       <li><a href="#implementing_local_references">Implementing Local References</a></li>
  44     </ul>
  45   </li>
  46   <li><a href="#accessing_java_objects">Accessing Java Objects</a>
  47     <ul>
  48       <li><a href="#accessing_primitive_arrays">Accessing Primitive Arrays</a></li>
  49       <li><a href="#accessing_fields_and_methods">Accessing Fields and Methods</a></li>
  50     </ul>
  51   </li>
  52 
  53   <li><a href="#java_exceptions">Java Exceptions</a>
  54     <ul>
  55       <li><a href="#exceptions_and_error_codes">Exceptions and Error Codes</a></li>
  56       <li><a href="#asynchronous_exceptions">Asynchronous Exceptions</a></li>
  57       <li><a href="#exception_handling">Exception Handling</a></li>
  58     </ul>
  59   </li>
  60 </ul>
  61 
  62 <h2><a name="jni_interface_functions_and_pointers">JNI Interface Functions and Pointers</a></h2>
  63 
  64 
  65 <p>Native code accesses Java VM features by calling
  66 JNI functions. JNI functions are available through an <em>interface pointer</em>. An interface pointer is a
  67 pointer to a pointer. This pointer points to an array of pointers,
  68 each of which points to an interface function. Every interface
  69 function is at a predefined offset inside the array. The following figure, <a href="#interface_pointer">Interface Pointer</a>, illustrates the
  70 organization of an interface pointer.</p>
  71 
  72 <img src="images/designa.gif" height="190"
  73 width="662" alt="Interface pointer"
  74 border="0" hspace="0" vspace="0" />
  75 
  76 <p><a name="interface_pointer"></a><a href="img_text/designa.html">Description of Figure Interface Pointer</a></p>
  77 
  78 
  79 <p>The JNI interface is organized like a C++ virtual
  80 function table or a COM interface. The advantage to using an
  81 interface table, rather than hard-wired function entries, is that
  82 the JNI name space becomes separate from the native code. A VM can
  83 easily provide multiple versions of JNI function tables. For
  84 example, the VM may support two JNI function tables:</p>
  85 
  86 
  87 <ul>
  88 <li>one performs thorough illegal argument checks, and is suitable
  89 for debugging;</li>
  90 <li>the other performs the minimal amount of checking required by
  91 the JNI specification, and is therefore more efficient.</li>
  92 </ul>
  93 
  94 
  95 <p>The JNI interface pointer is only valid in the
  96 current thread. A native method, therefore, must not pass the
  97 interface pointer from one thread to another. A VM implementing the
  98 JNI may allocate and store thread-local data in the area pointed to
  99 by the JNI interface pointer.</p>
 100 
 101 <p>Native methods receive the JNI interface pointer
 102 as an argument. The VM is guaranteed to pass the same interface
 103 pointer to a native method when it makes multiple calls to the
 104 native method from the same Java thread. However, a native method
 105 can be called from different Java threads, and therefore may
 106 receive different JNI interface pointers.</p>
 107 
 108 <h2><a name="compiling_loading_and_linking_native_methods">Compiling, Loading and Linking Native
 109 Methods</a></h2>
 110 
 111 <p>Since the Java VM is multithreaded, native
 112 libraries should also be compiled and linked with multithread aware
 113 native compilers. For example, the <code>-mt</code>
 114 flag should be used for C++ code compiled with the Sun Studio
 115 compiler. For code complied with the GNU gcc compiler, the flags
 116 <code>-D_REENTRANT</code> or <code>-D_POSIX_C_SOURCE</code> should be used. For more
 117 information please refer to the native compiler documentation.</p>
 118 <p>Native methods are loaded with the <code>System.loadLibrary</code> method. In the following example,
 119 the class initialization method loads a platform-specific native
 120 library in which the native method <code>f</code> is
 121 defined:</p>
 122 
 123 <pre class="codeblock">package pkg; 
 124 
 125 class Cls {
 126     native double f(int i, String s);
 127     static {
 128         System.loadLibrary(&ldquo;pkg_Cls&rdquo;);
 129     }
 130 }</pre>
 131 
 132 <p>The argument to <code>System.loadLibrary</code> is a library name chosen
 133 arbitrarily by the programmer. The system follows a standard, but
 134 platform-specific, approach to convert the library name to a native
 135 library name. For example, a Solaris system converts the name
 136 <code>pkg_Cls</code> to <code>libpkg_Cls.so</code>, while a Win32 system converts the
 137 same <code>pkg_Cls</code> name to <code>pkg_Cls.dll</code>.</p>
 138 
 139 <p>The programmer may use a single library to store
 140 all the native methods needed by any number of classes, as long as
 141 these classes are to be loaded with the same class loader. The VM
 142 internally maintains a list of loaded native libraries for each
 143 class loader. Vendors should choose native library names that
 144 minimize the chance of name clashes.</p>
 145 
 146 <p>A native library may be statically linked with the VM.  
 147 The manner in which the library and VM image are combined is implementation
 148 dependent. 
 149 </p>
 150 
 151 <p>A <code>System.loadLibrary</code> or equivalent 
 152 API must succeed for this library to be considered loaded.
 153 </p>
 154 
 155 <p>A library L whose image has been combined with the VM is 
 156 defined as statically linked if and only if the library exports a function 
 157 called <code>JNI_OnLoad_L</code>.
 158 </p>
 159 
 160 <p>If a statically linked library L exports a function called 
 161 <code>JNI_OnLoad_L</code> and a function called 
 162 <code>JNI_OnLoad</code>, the <code>JNI_OnLoad</code> 
 163 function will be ignored.
 164 </p>
 165 
 166 <p>If a library L is statically linked, then upon the first invocation of 
 167 <code>System.loadLibrary("L")</code> or equivalent API, a 
 168 <code>JNI_OnLoad_L</code> function will be invoked with the same arguments 
 169 and expected return value as specified for the <code>JNI_OnLoad function</code>.
 170 </p>
 171 
 172 <p>A library L that is statically linked will prohibit a library 
 173 of the same name from being loaded dynamically.
 174 </p>
 175 
 176 <p>When the class loader containing a statically linked native library L 
 177 is garbage collected, the VM will invoke the <code>JNI_OnUnload_L</code> 
 178 function of the library if such a function is exported.
 179 </p>
 180 
 181 <p>If a statically linked library L exports a function called 
 182 <code>JNI_OnUnLoad_L</code> and a function called 
 183 <code>JNI_OnUnLoad</code>, the <code>JNI_OnUnLoad</code> 
 184 function will be ignored.
 185 </p>
 186 
 187 <p>The programmer can also call the JNI function
 188 <code>RegisterNatives()</code> to register the native
 189 methods associated with a class. The <code>RegisterNatives()</code> function is particularly useful
 190 with statically linked functions.</p>
 191 
 192 <h3><a name="resolving_native_method_names">Resolving Native Method Names</a></h3>
 193 
 194 <p>Dynamic linkers resolve entries based on their
 195 names. A native method name is concatenated from the following
 196 components:</p>
 197 
 198 
 199 <ul>
 200 <li>the prefix <code>Java_</code></li>
 201 <li>a mangled fully-qualified class name</li>
 202 <li>an underscore (&ldquo;_&rdquo;) separator</li>
 203 <li>a mangled method name</li>
 204 <li>for overloaded native methods, two underscores
 205 (&ldquo;__&rdquo;) followed by the mangled argument signature</li>
 206 </ul>
 207 
 208 
 209 
 210 <p>The VM checks for a method name match for methods
 211 that reside in the native library. The VM looks first for the short
 212 name; that is, the name without the argument signature. It then
 213 looks for the long name, which is the name with the argument
 214 signature. Programmers need to use the long name only when a native
 215 method is overloaded with another native method. However, this is
 216 not a problem if the native method has the same name as a nonnative
 217 method. A nonnative method (a Java method) does not reside in the
 218 native library.</p>
 219 
 220 <p>In the following example, the native method
 221 <code>g</code> does not have to be linked using the
 222 long name because the other method <code>g</code> is
 223 not a native method, and thus is not in the native library.</p>
 224 
 225 <pre class="codeblock">class Cls1 {
 226     int g(int i);
 227     native int g(double d);
 228 }</pre>
 229 
 230 <p>We adopted a simple name-mangling scheme to ensure
 231 that all Unicode characters translate into valid C function names.
 232 We use the underscore (&ldquo;_&rdquo;) character as the substitute
 233 for the slash (&ldquo;/&rdquo;) in fully qualified class names.
 234 Since a name or type descriptor never begins with a number, we can
 235 use <code>_0</code>, ..., <code>_9</code> for escape sequences, as the following table illustrates:</p>
 236 
 237 <table border="1" summary="Unicode character translations">
 238 <caption>Unicode Character Translation</caption>
 239 <thead>
 240 <tr>
 241   <th>Escape Sequence</th>
 242   <th>Denotes</th>
 243 </tr>
 244 </thead>
 245 <tr>
 246 <td>
 247 <code>_0XXXX</code>
 248 </td>
 249 <td>
 250 a Unicode character <code>XXXX</code>. Note that lower case is used to represent non-ASCII Unicode characters, for example, <code>_0abcd</code> as opposed to <code>_0ABCD</code>.
 251 </td>
 252 </tr>
 253 <tr>
 254 <td>
 255 <code>_1</code>
 256 </td>
 257 <td>
 258 the character &ldquo;_&rdquo;
 259 </td>
 260 </tr>
 261 <tr>
 262 <td>
 263 <code>_2</code>
 264 </td>
 265 <td>
 266 the character &ldquo;;&rdquo; in
 267 signatures
 268 </td>
 269 </tr>
 270 <tr>
 271 <td>
 272 <code>_3</code>
 273 </td>
 274 <td>
 275 the character &ldquo;[&ldquo; in
 276 signatures
 277 </td>
 278 </tr>
 279 </table>
 280 
 281 <p>Both the native methods and the interface APIs
 282 follow the standard library-calling convention on a given platform.
 283 For example, UNIX systems use the C calling convention, while Win32
 284 systems use __stdcall.</p>
 285 
 286 <h3><a name="native_method_arguments">Native Method Arguments</a></h3>
 287 
 288 <p>The JNI interface pointer is the first argument to
 289 native methods. The JNI interface pointer is of type <em>JNIEnv</em>. The second argument differs depending on
 290 whether the native method is static or nonstatic. The second
 291 argument to a nonstatic native method is a reference to the object.
 292 The second argument to a static native method is a reference to its
 293 Java class.</p>
 294 <p>The remaining arguments correspond to regular Java
 295 method arguments. The native method call passes its result back to
 296 the calling routine via the return value. <a href=
 297 "types.html">Chapter 3: JNI Types and Data Structures</a> describes the mapping
 298 between Java and C types.</p>
 299 
 300 <p>The following code example illustrates
 301 using a C function to implement the native method <code>f</code>. The native method <code>f</code> is
 302 declared as follows:</p>
 303 
 304 <pre class="codeblock">package pkg; 
 305 
 306 class Cls {
 307     native double f(int i, String s);
 308     // ...
 309 }</pre>
 310 
 311 <p>The C function with the long mangled name
 312 <code>Java_pkg_Cls_f_ILjava_lang_String_2</code>
 313 implements native method <code>f</code>:</p>
 314 
 315 <pre class="codeblock">jdouble Java_pkg_Cls_f__ILjava_lang_String_2 (
 316      JNIEnv *env,        /* interface pointer */
 317      jobject obj,        /* "this" pointer */
 318      jint i,             /* argument #1 */
 319      jstring s)          /* argument #2 */
 320 {
 321      /* Obtain a C-copy of the Java string */
 322      const char *str = (*env)-&gt;GetStringUTFChars(env, s, 0);
 323 
 324      /* process the string */
 325      ...
 326 
 327      /* Now we are done with str */
 328      (*env)-&gt;ReleaseStringUTFChars(env, s, str);
 329 
 330      return ...
 331 }</pre>
 332 
 333 <p>Note that we always manipulate Java objects using
 334 the interface pointer <em>env</em>. Using C++, you can write a slightly cleaner
 335 version of the code, as shown in the following code example:</p>
 336 
 337 <pre class="codeblock">extern "C" /* specify the C calling convention */ 
 338 
 339 jdouble Java_pkg_Cls_f__ILjava_lang_String_2 (
 340 
 341      JNIEnv *env,        /* interface pointer */
 342      jobject obj,        /* "this" pointer */
 343      jint i,             /* argument #1 */
 344      jstring s)          /* argument #2 */
 345 
 346 {
 347      const char *str = env-&gt;GetStringUTFChars(s, 0);
 348 
 349      // ...
 350 
 351      env-&gt;ReleaseStringUTFChars(s, str);
 352 
 353      // return ...
 354 }</pre>
 355 
 356 <p>With C++, the extra level of indirection and the
 357 interface pointer argument disappear from the source code. However,
 358 the underlying mechanism is exactly the same as with C. In C++, JNI
 359 functions are defined as inline member functions that expand to
 360 their C counterparts.</p>
 361 
 362 <h2><a name="referencing_java_objects">Referencing Java Objects</a></h2>
 363 
 364 <p>Primitive types, such as integers, characters, and
 365 so on, are copied between Java and native code. Arbitrary Java
 366 objects, on the other hand, are passed by reference. The VM must
 367 keep track of all objects that have been passed to the native code,
 368 so that these objects are not freed by the garbage collector. The
 369 native code, in turn, must have a way to inform the VM that it no
 370 longer needs the objects. In addition, the garbage collector must
 371 be able to move an object referred to by the native code.</p>
 372 
 373 <h3><a name="global_and_local_references">Global and Local References</a></h3>
 374 
 375 <p>The JNI divides object references used by the
 376 native code into two categories: <em>local</em>
 377 and <em>global references</em>. Local references
 378 are valid for the duration of a native method call, and are
 379 automatically freed after the native method returns. Global
 380 references remain valid until they are explicitly freed.</p>
 381 
 382 <p>Objects are passed to native methods as local
 383 references. All Java objects returned by JNI functions are local
 384 references. The JNI allows the programmer to create global
 385 references from local references. JNI functions that expect Java
 386 objects accept both global and local references. A native method
 387 may return a local or global reference to the VM as its result.</p>
 388 
 389 <p>In most cases, the programmer should rely on the
 390 VM to free all local references after the native method returns.
 391 However, there are times when the programmer should explicitly free
 392 a local reference. Consider, for example, the following
 393 situations:</p>
 394 
 395 
 396 <ul>
 397 <li>A native method accesses a large Java object, thereby creating
 398 a local reference to the Java object. The native method then
 399 performs additional computation before returning to the caller. The
 400 local reference to the large Java object will prevent the object
 401 from being garbage collected, even if the object is no longer used
 402 in the remainder of the computation.</li>
 403 <li>A native method creates a large number of local references,
 404 although not all of them are used at the same time. Since the VM
 405 needs a certain amount of space to keep track of a local reference,
 406 creating too many local references may cause the system to run out
 407 of memory. For example, a native method loops through a large array
 408 of objects, retrieves the elements as local references, and
 409 operates on one element at each iteration. After each iteration,
 410 the programmer no longer needs the local reference to the array
 411 element.</li>
 412 </ul>
 413 
 414 
 415 
 416 <p>The JNI allows the programmer to manually delete
 417 local references at any point within a native method. To ensure
 418 that programmers can manually free local references, JNI functions
 419 are not allowed to create extra local references, except for
 420 references they return as the result.</p>
 421 
 422 <p>Local references are only valid in the thread in
 423 which they are created. The native code must not pass local
 424 references from one thread to another.</p>
 425 
 426 <h3><a name="implementing_local_references">Implementing Local References</a></h3>
 427 
 428 <p>To implement local references, the Java VM creates
 429 a registry for each transition of control from Java to a native
 430 method. A registry maps nonmovable local references to Java
 431 objects, and keeps the objects from being garbage collected. All
 432 Java objects passed to the native method (including those that are
 433 returned as the results of JNI function calls) are automatically
 434 added to the registry. The registry is deleted after the native
 435 method returns, allowing all of its entries to be garbage
 436 collected.</p>
 437 
 438 <p>There are different ways to implement a registry,
 439 such as using a table, a linked list, or a hash table. Although
 440 reference counting may be used to avoid duplicated entries in the
 441 registry, a JNI implementation is not obliged to detect and
 442 collapse duplicate entries.</p>
 443 
 444 <p>Note that local references cannot be faithfully
 445 implemented by conservatively scanning the native stack. The native
 446 code may store local references into global or heap data
 447 structures.</p>
 448 
 449 <h2><a name="accessing_java_objects">Accessing Java Objects</a></h2>
 450 
 451 <p>The JNI provides a rich set of accessor functions
 452 on global and local references. This means that the same native
 453 method implementation works no matter how the VM represents Java
 454 objects internally. This is a crucial reason why the JNI can be
 455 supported by a wide variety of VM implementations.</p>
 456 
 457 <p>The overhead of using accessor functions through
 458 opaque references is higher than that of direct access to C data
 459 structures. We believe that, in most cases, Java programmers use
 460 native methods to perform nontrivial tasks that overshadow the
 461 overhead of this interface.</p>
 462 
 463 <h3><a name="accessing_primitive_arrays">Accessing Primitive Arrays</a></h3>
 464 
 465 <p>This overhead is not acceptable for large Java
 466 objects containing many primitive data types, such as integer
 467 arrays and strings. (Consider native methods that are used to
 468 perform vector and matrix calculations.) It would be grossly
 469 inefficient to iterate through a Java array and retrieve every
 470 element with a function call.</p>
 471 
 472 <p>One solution introduces a notion of
 473 &ldquo;pinning&rdquo; so that the native method can ask the VM to
 474 pin down the contents of an array. The native method then receives
 475 a direct pointer to the elements. This approach, however, has two
 476 implications:</p>
 477 
 478 
 479 <ul>
 480 <li>The garbage collector must support pinning.</li>
 481 <li>The VM must lay out primitive arrays contiguously in memory.
 482 Although this is the most natural implementation for most primitive
 483 arrays, boolean arrays can be implemented as packed or unpacked.
 484 Therefore, native code that relies on the exact layout of boolean
 485 arrays will not be portable.</li>
 486 </ul>
 487 
 488 
 489 
 490 <p>We adopt a compromise that overcomes both of the
 491 above problems.</p>
 492 
 493 <p>First, we provide a set of functions to copy
 494 primitive array elements between a segment of a Java array and a
 495 native memory buffer. Use these functions if a native method needs
 496 access to only a small number of elements in a large array.</p>
 497 
 498 <p>Second, programmers can use another set of
 499 functions to retrieve a pinned-down version of array elements. Keep
 500 in mind that these functions may require the Java VM to perform
 501 storage allocation and copying. Whether these functions in fact
 502 copy the array depends on the VM implementation, as follows:</p>
 503 
 504 
 505 <ul>
 506 <li>If the garbage collector supports pinning, and the layout of
 507 the array is the same as expected by the native method, then no
 508 copying is needed.</li>
 509 <li>Otherwise, the array is copied to a nonmovable memory block
 510 (for example, in the C heap) and the necessary format conversion is
 511 performed. A pointer to the copy is returned.</li>
 512 </ul>
 513 
 514 
 515 
 516 <p>Lastly, the interface provides functions to inform
 517 the VM that the native code no longer needs to access the array
 518 elements. When you call these functions, the system either unpins
 519 the array, or it reconciles the original array with its non-movable
 520 copy and frees the copy.</p>
 521 
 522 <p>Our approach provides flexibility. A garbage
 523 collector algorithm can make separate decisions about copying or
 524 pinning for each given array. For example, the garbage collector
 525 may copy small objects, but pin the larger objects.</p>
 526 
 527 <p>A JNI implementation must ensure that native
 528 methods running in multiple threads can simultaneously access the
 529 same array. For example, the JNI may keep an internal counter for
 530 each pinned array so that one thread does not unpin an array that
 531 is also pinned by another thread. Note that the JNI does not need
 532 to lock primitive arrays for exclusive access by a native method.
 533 Simultaneously updating a Java array from different threads leads
 534 to nondeterministic results.</p>
 535 
 536 <h3><a name="accessing_fields_and_methods">Accessing Fields and Methods</a></h3>
 537 
 538 <p>The JNI allows native code to access the fields
 539 and to call the methods of Java objects. The JNI identifies methods
 540 and fields by their symbolic names and type signatures. A two-step
 541 process factors out the cost of locating the field or method from
 542 its name and signature. For example, to call the method
 543 <code>f</code> in class <em>cls</em>, the native code
 544 first obtains a method ID, as follows:</p>
 545 
 546 <pre class="codeblock">jmethodID mid = env-&gt;GetMethodID(cls, &ldquo;f&rdquo;, &ldquo;(ILjava/lang/String;)D&rdquo;);</pre>
 547 
 548 <p>The native code can then use the method ID
 549 repeatedly without the cost of method lookup, as follows:</p>
 550 
 551 <pre class="codeblock">jdouble result = env-&gt;CallDoubleMethod(obj, mid, 10, str);</pre>
 552 
 553 <p>A field or method ID does not prevent the VM from
 554 unloading the class from which the ID has been derived. After the
 555 class is unloaded, the method or field ID becomes invalid. The
 556 native code, therefore, must make sure to:</p>
 557 
 558 
 559 <ul>
 560 <li>keep a live reference to the underlying class, or</li>
 561 <li>recompute the method or field ID</li>
 562 </ul>
 563 
 564 
 565 
 566 <p>if it intends to use a method or field ID for an
 567 extended period of time.</p>
 568 <p>The JNI does not impose any restrictions on how
 569 field and method IDs are implemented internally.</p>
 570 
 571 <h2><a name="reporting_programming_errors">Reporting Programming Errors</a></h2>
 572 
 573 <p>The JNI does not check for programming errors such
 574 as passing in NULL pointers or illegal argument types. Illegal
 575 argument types includes such things as using a normal Java object
 576 instead of a Java class object. The JNI does not check for these
 577 programming errors for the following reasons:</p>
 578 
 579 
 580 <ul>
 581 <li>Forcing JNI functions to check for all possible error
 582 conditions degrades the performance of normal (correct) native
 583 methods.</li>
 584 <li>In many cases, there is not enough runtime type information to
 585 perform such checking.</li>
 586 </ul>
 587 
 588 
 589 
 590 <p>Most C library functions do not guard against
 591 programming errors. The <code>printf()</code>
 592 function, for example, usually causes a runtime error, rather than
 593 returning an error code, when it receives an invalid address.
 594 Forcing C library functions to check for all possible error
 595 conditions would likely result in such checks to be
 596 duplicated--once in the user code, and then again in the
 597 library.</p>
 598 
 599 <p>The programmer must not pass illegal pointers or
 600 arguments of the wrong type to JNI functions. Doing so could result
 601 in arbitrary consequences, including a corrupted system state or VM
 602 crash.</p>
 603 
 604 <h2><a name="java_exceptions">Java Exceptions</a></h2>
 605 
 606 <p>The JNI allows native methods to raise arbitrary
 607 Java exceptions. The native code may also handle outstanding Java
 608 exceptions. The Java exceptions left unhandled are propagated back
 609 to the VM.</p>
 610 
 611 <h3><a name="exceptions_and_error_codes">Exceptions and Error Codes</a></h3>
 612 
 613 <p>Certain JNI functions use the Java exception
 614 mechanism to report error conditions. In most cases, JNI functions
 615 report error conditions by returning an error code <em>and</em> throwing a Java exception. The error code is
 616 usually a special return value (such as NULL) that is outside of
 617 the range of normal return values. Therefore, the programmer
 618 can:</p>
 619 
 620 
 621 <ul>
 622 <li>quickly check the return value of the last JNI call to
 623 determine if an error has occurred, and</li>
 624 <li>call a function, <code>ExceptionOccurred()</code>, to obtain the exception object
 625 that contains a more detailed description of the error
 626 condition.</li>
 627 </ul>
 628 
 629 
 630 
 631 <p>There are two cases where the programmer needs to
 632 check for exceptions without being able to first check an error
 633 code:</p>
 634 
 635 
 636 <ul>
 637 <li>The JNI functions that invoke a Java method return the result
 638 of the Java method. The programmer must call <code>ExceptionOccurred()</code> to check for possible exceptions
 639 that occurred during the execution of the Java method.</li>
 640 <li>Some of the JNI array access functions do not return an error
 641 code, but may throw an <code>ArrayIndexOutOfBoundsException</code> or <code>ArrayStoreException</code>.</li>
 642 </ul>
 643 
 644 
 645 
 646 <p>In all other cases, a non-error return value
 647 guarantees that no exceptions have been thrown.</p>
 648 
 649 <h3><a name="asynchronous_exceptions">Asynchronous Exceptions</a></h3>
 650 
 651 <p>One thread may raise an asynchronous exception in another thread by calling
 652 the <code>Thread.stop()</code> method, which has been deprecated since Java 2
 653 SDK release 1.2. Programmers are strongly discouraged from using
 654 <code>Thread.stop()</code> as it generally leads to an indeterminate application
 655 state.</p>
 656 
 657 <p>Furthermore, the JVM may produce exceptions in the current thread without
 658 being the direct result of a JNI API call, but because of various JVM internal
 659 errors, for example: <code>VirtualMachineError</code> like
 660 <code>StackOverflowError</code> or <code>OutOfMemoryError</code>. These are also
 661 referred to as asynchronous exceptions.</p>
 662 
 663 <p>Asynchronous exceptions do not immediately affect the execution of the native
 664 code in the current thread, until:</p>
 665 
 666 <ul>
 667   <li>the native code calls one of the JNI functions that could raise synchronous
 668     exceptions, or</li>
 669 
 670   <li>the native code uses <code>ExceptionOccurred()</code> to explicitly check
 671     for synchronous and asynchronous exceptions.</li>
 672 </ul>
 673 
 674 <p>Note that only those JNI functions that could potentially raise synchronous
 675 exceptions check for asynchronous exceptions.</p>
 676 
 677 <p>Native methods should insert <code>ExceptionOccurred()</code> checks in
 678 necessary places, such as in any long running code without other exception
 679 checks (this may include tight loops). This ensures that the current thread
 680 responds to asynchronous exceptions in a reasonable amount of time. However,
 681 because of their asynchronous nature, making an exception check before a call is
 682 no guarantee that an asynchronous exception won't be raised between the check
 683 and the call.</p>
 684 
 685 
 686 <h3><a name="exception_handling">Exception Handling</a></h3>
 687 
 688 <p>There are two ways to handle an exception in
 689 native code:</p>
 690 
 691 
 692 <ul>
 693 <li>The native method can choose to return immediately, causing the
 694 exception to be thrown in the Java code that initiated the native
 695 method call.</li>
 696 <li>The native code can clear the exception by calling <code>ExceptionClear()</code>, and then execute its own
 697 exception-handling code.</li>
 698 </ul>
 699 
 700 
 701 
 702 <p>After an exception has been raised, the native
 703 code must first clear the exception before making other JNI calls.
 704 When there is a pending exception, the JNI functions that are safe
 705 to call are:</p>
 706 
 707 <pre class="codeblock">ExceptionOccurred()
 708 ExceptionDescribe()
 709 ExceptionClear()
 710 ExceptionCheck()
 711 ReleaseStringChars()
 712 ReleaseStringUTFChars()
 713 ReleaseStringCritical()
 714 Release&lt;Type&gt;ArrayElements()
 715 ReleasePrimitiveArrayCritical()
 716 DeleteLocalRef()
 717 DeleteGlobalRef()
 718 DeleteWeakGlobalRef()
 719 MonitorExit()
 720 PushLocalFrame()
 721 PopLocalFrame()</pre>
 722 
 723 <table width="100%" summary="">
 724 <tr>
 725 <td><a accesskey="c" href="jniTOC.html">Contents</a> |
 726 <a accesskey="p" href="intro.html">Previous</a> | <a accesskey="n"
 727 href="types.html">Next</a></td>
 728 <td align="right"></td>
 729 </tr>
 730 </table>
 731 </body>
 732 </html>