HOME

TheInfoList



OR:

In software design, the Java Native Interface (JNI) is a
foreign function interface A foreign function interface (FFI) is a mechanism by which a program written in one programming language can call routines or make use of services written in another. Naming The term comes from the specification for Common Lisp, which explicit ...
programming framework that enables
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
code running in a Java virtual machine (JVM) to call and be called by native applications (programs specific to a hardware and
operating system An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. Time-sharing operating systems schedule tasks for efficient use of the system and may also i ...
platform) and
libraries A library is a collection of Document, materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or electronic media, digital access (soft copies) materials, and may be a ...
written in other languages such as C,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
and
assembly Assembly may refer to: Organisations and meetings * Deliberative assembly, a gathering of members who use parliamentary procedure for making decisions * General assembly, an official meeting of the members of an organization or of their representa ...
.


Objectives

JNI enables programmers to write native methods to handle situations when an application cannot be written entirely in the Java programming language, e.g. when the standard Java
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
library A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vir ...
does not support the platform-specific features or program library. It is also used to modify an existing application (written in another programming language) to be accessible to Java applications. Many of the standard library classes depend on JNI to provide functionality to the developer and the user, e.g. file I/O and sound capabilities. Including performance- and platform-sensitive API implementations in the standard library allows all Java applications to access this functionality in a safe and platform-independent manner. The JNI framework lets a native method use Java
objects Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
in the same way that Java code uses these objects. A native method can create Java objects and then inspect and use these objects to perform its tasks. A native method can also inspect and use objects created by Java application code. Only applications and signed applets can invoke JNI. An application that relies on JNI loses the platform portability Java offers (a partial workaround is to write a separate implementation of JNI code for each platform and have Java detect the operating system and load the correct one at runtime). Not only can native code interface with Java, it can also draw on a Java , which is possible with the
Java AWT Native Interface Java AWT Native Interface (jawt) is an interface for the Java programming language that enables rendering libraries compiled to native code to draw directly to a Java Abstract Window Toolkit (AWT) object drawing surface. The Java Native Interf ...
. The process is almost the same, with just a few changes. The Java AWT Native Interface is only available since J2SE 1.3. JNI also allows direct access to
assembly code In computer programming, assembly language (or assembler language, or symbolic machine code), often referred to simply as Assembly and commonly abbreviated as ASM or asm, is any low-level programming language with a very strong correspondence b ...
, without even going through a C bridge. Accessing Java applications from assembly is possible in the same way.


Design

In the JNI framework, native functions are implemented in separate .c or .cpp files. (C++ provides a slightly simpler interface with JNI.) When the JVM invokes the function, it passes a JNIEnv pointer, a jobject pointer, and any Java arguments declared by the Java method. For example, the following converts a Java string to a native string: extern "C" JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj, jstring javaString) The ''env'' pointer is a structure that contains the interface to the JVM. It includes all of the functions necessary to interact with the JVM and to work with Java objects. Example JNI functions are converting native arrays to/from Java arrays, converting native strings to/from Java strings, instantiating objects, throwing exceptions, etc. Basically, anything that Java code can do can be done using JNIEnv, albeit with considerably less ease. The argument ''obj'' is a reference to the Java object inside which this native method has been declared. Native data types can be mapped to/from Java data types. For compound types such as objects,
arrays An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
and strings the native code must explicitly convert the data by calling methods in the JNIEnv. A JNI environment pointer () is passed as an argument for each native function mapped to a Java method, allowing for interaction with the JNI environment within the native method. This JNI interface pointer can be stored, but remains valid only in the current thread. Other threads must first call to attach themselves to the VM and obtain a JNI interface pointer. Once attached, a native thread works like a regular Java thread running within a native method. The native thread remains attached to the VM until it calls to detach itself.The Invocation API. Sun Microsystems. https://docs.oracle.com/en/java/javase/11/docs/specs/jni/invocation.html The JNI framework does not provide any automatic garbage collection for non-JVM memory resources allocated by code executing on the native side. Consequently, native side code (such as assembly language) assumes the responsibility for explicitly releasing any such memory resources that the native code acquires. On Linux and Solaris platforms, if the native code registers itself as a signal handler, it could intercept signals intended for the JVM. A
chain of responsibility The chain of responsibility is a policy concept used in Australian transport legislation to place legal obligations on parties in the transport supply chain or across transport industries generally. The concept was initially developed to apply ...
can be used to allow native code to better inter-operate with the JVM. On Windows platforms, Structured Exception Handling (SEH) may be employed to wrap native code in SEH try/catch blocks so as to capture machine (CPU/FPU) generated software interrupts (such as NULL pointer access violations and divide-by-zero operations), and to handle these situations before the interrupt is propagated back up into the JVM (i.e. Java side code), in all likelihood resulting in an unhandled exception. The encoding used for the NewStringUTF, GetStringUTFLength, GetStringUTFChars, ReleaseStringUTFChars and GetStringUTFRegion functions is "modified UTF-8", which is not valid UTF-8 for all inputs, but a different encoding really. The null character (U+0000) and codepoints not on the
Basic Multilingual Plane In the Unicode standard, a plane is a continuous group of 65,536 (216) code points. There are 17 planes, identified by the numbers 0 to 16, which corresponds with the possible values 00–1016 of the first two positions in six position hexadecima ...
(greater than or equal to U+10000, i.e. those represented as ''surrogate pairs'' in UTF-16) are encoded differently in modified UTF-8. Many programs actually use these functions incorrectly and treat the UTF-8 strings returned or passed into the functions as standard UTF-8 strings instead of modified UTF-8 strings. Programs should use the NewString, GetStringLength, GetStringChars, ReleaseStringChars, GetStringRegion, GetStringCritical and ReleaseStringCritical functions, which use UTF-16LE encoding on little-endian architectures and UTF-16BE on big-endian architectures, and then use a UTF-16 to UTF-8 conversion routine.


Mapping types

The following table shows the mapping of types between Java (JNI) and native code. In addition, the signature "L qualified-class ;" would mean the class uniquely specified by that name; e.g., the signature "Ljava/lang/String;" refers to the class java.lang.String. Also, prefixing
typecast_ In_film,_television,_and_theatre,_typecasting_is_the_process_by_which_a_particular_actor_becomes_strongly_identified_with_a_specific_character,_one_or_more_particular_roles,_or_characters_having_the_same__traits_or_coming_from_the_same_social_or__...
ing_required._However,_mapping_between_Java_Strings_and_arrays_to_native_strings_and_arrays_is_different._If_a_jstring_is_used_where_a_char_*_would_be,_the_code_could_crash_the_JVM.


__Performance_

JNI_incurs_considerable_overhead_and_performance_loss_under_certain_circumstances: *_Function_calls_to_JNI_methods_are_expensive,_especially_when_calling_a_method_repeatedly. *_Native_methods_are_not_inlined_by_the_JVM,_nor_can_the_method_be_
typecast_ In_film,_television,_and_theatre,_typecasting_is_the_process_by_which_a_particular_actor_becomes_strongly_identified_with_a_specific_character,_one_or_more_particular_roles,_or_characters_having_the_same__traits_or_coming_from_the_same_social_or__...
ing_required._However,_mapping_between_Java_Strings_and_arrays_to_native_strings_and_arrays_is_different._If_a_jstring_is_used_where_a_char_*_would_be,_the_code_could_crash_the_JVM.


__Performance_

JNI_incurs_considerable_overhead_and_performance_loss_under_certain_circumstances: *_Function_calls_to_JNI_methods_are_expensive,_especially_when_calling_a_method_repeatedly. *_Native_methods_are_not_inlined_by_the_JVM,_nor_can_the_method_be_Just-in-time_compilation">JIT_compiled,_as_the_method_is_already_compiled. *_A_Java_array_may_be_copied_for_access_in_native_code,_and_later_copied_back._The_cost_can_be_linear_in_the_size_of_the_array. *_If_the_method_is_passed_an_object,_or_needs_to_make_a_callback,_then_the_native_method_will_likely_be_making_its_own_calls_to_the_JVM._Accessing_Java_fields,_methods_and_types_from_the_native_code_requires_something_similar_to_Reflection_(computer_programming).html" "title="Just-in-time_compilation.html" ;"title="type_conversion.html" "title="/code> to the signature makes the array of that type; for example, [I means the int array type. Finally, a void signature uses the V code. These types are interchangeable. One can use jint where you normally use an int, and vice versa, without any type conversion">typecast In film, television, and theatre, typecasting is the process by which a particular actor becomes strongly identified with a specific character, one or more particular roles, or characters having the same traits or coming from the same social or ...
ing required. However, mapping between Java Strings and arrays to native strings and arrays is different. If a jstring is used where a char * would be, the code could crash the JVM.


Performance

JNI incurs considerable overhead and performance loss under certain circumstances: * Function calls to JNI methods are expensive, especially when calling a method repeatedly. * Native methods are not inlined by the JVM, nor can the method be Just-in-time compilation">JIT compiled, as the method is already compiled. * A Java array may be copied for access in native code, and later copied back. The cost can be linear in the size of the array. * If the method is passed an object, or needs to make a callback, then the native method will likely be making its own calls to the JVM. Accessing Java fields, methods and types from the native code requires something similar to Reflection (computer programming)">reflection Reflection or reflexion may refer to: Science and technology * Reflection (physics), a common wave phenomenon ** Specular reflection, reflection from a smooth surface *** Mirror image, a reflection in a mirror or in water ** Signal reflection, in ...
. Signatures are specified in strings and queried from the JVM. This is both slow and error-prone. * Java Strings are objects, have length and are encoded. Accessing or creating a string may require an O(n) copy.


Alternatives

Microsoft's proprietary implementation of a Java Virtual Machine (
Visual J++ Visual J++ is Microsoft's discontinued implementation of Java. Syntax, keywords, and grammatical conventions were the same as Java's. It was introduced in 1996 and discontinued in January 2004, replaced to a certain extent by J# and C#. The i ...
) had a similar mechanism for calling native code from Java, called the ''Raw Native Interface'' (''RNI''). In addition, it had an easy way to call existing native code that wasn't itself aware of Java, such as (but not limited to) the Windows API, called ''J/Direct''. However, following the Sun–Microsoft litigation about this implementation,
Visual J++ Visual J++ is Microsoft's discontinued implementation of Java. Syntax, keywords, and grammatical conventions were the same as Java's. It was introduced in 1996 and discontinued in January 2004, replaced to a certain extent by J# and C#. The i ...
is no longer maintained. RNI was less clumsy to use than JNI, because no bookkeeping with a Java environment pointer was needed. Instead, all Java objects could be accessed directly. To facilitate this, a tool was used that generated header files from Java classes. Similarly, J/Direct was easier to use than using the necessary intermediate native library and JNI. Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using JNI.


See also

* GIWS (software) *
Gluegen GlueGen is a Java tool which automatically generates the Java and Java Native Interface (JNI) code needed to call C libraries from Java code. It reads in ANSI C header files and GlueGen configuration files, and emits C code. As JNI can be complex ...
* Platform Invocation Services * SWIG


References


Bibliography

* * {{refend


External links


Oracle's JNI 6.0 API Specification

Java Native Interface: Programmer's Guide and Specification



Exception handling in JNI

Java Link
(modern C++17 wrapper for JNI) Java platform