One of the main factors hindering Java's wide application is the efficiency of Java program running. Java is a language between the interpreted and compiled types. If the same program is implemented using the compiled language C, the running speed is generally more than doubled than that of Java. Java has platform independence, which makes it one of the main candidates when developing enterprise-level applications. However, performance factors have greatly weakened its competitiveness. Therefore, it is very important to improve Java performance.
Question proposal
Sun and Java's supporters have made a lot of effort to speed up java, most of which focus on programming methods and pattern selection. Because the optimization of algorithms and design patterns is universal, effective optimization algorithms and design patterns for Java are also applicable to other compilation languages, therefore, the difference in execution efficiency between Java programs and compiled languages cannot be fundamentally changed.
JIT (just in time, timely compilation) technology is a good idea. The basic principle is: first, the Java source code is compiled into a platform-independent binary bytecode through the Java compiler. Then, before the Java program is actually executed, the system uses the JIT compiler to compile the Java bytecode into a localized machine code. Finally, the system executes the local machine code, saving time for interpreting the bytecode. This greatly improves the performance of Java programs and shortens the loading time. At the same time, compilation results are not saved between programs, thus saving storage space. The disadvantage is that the JIT compiler also takes a lot of time to optimize all the code.
Dynamic Optimization is another attempt to improve Java performance. This technology attempts to improve Java performance by directly compiling Java source programs into machine code to fully utilize Java Dynamic compilation and static compilation technologies. This method converts the input Java source code or bytecode to a highly optimized executable code and dynamic library (A. dll file in Windows or a. So file in UNIX ). This technology can greatly improve the performance of the program, but damages the portability of Java.
JNI technology
In fact, there is a technology that we usually ignore that can solve this problem to a large extent, that is, JNI (Java Native Interface, Java localization method ). Those who advocate the use of pure Java are usually opposed to the use of localized code. They believe that calling C/C ++ programs during Java program execution will affect program portability and security. Some people think that JNI is only a simple extension of Mixed Programming Technology in the past, and its actual purpose is to make full use of a large number of original C libraries.
In fact, we do not have to stick to the strict restrictions on platform independence, because the use of JNI technology is only for some code segments that seriously affect Java performance, this Part may only occupy a very small part of the source program, therefore, we can almost ignore the workload of porting this part of code between mainstream platforms. At the same time, we do not have to worry about the type matching problem. We can control the code to avoid this error. In addition, you do not have to worry about security control because the Java security model has been extended to allow non-system classes to load and call local methods. According to Java specifications, from JDK 1.2, findclass will try to find the Class Loader associated with the current local method. If the platform-related code belongs to a system class, no class loader is involved. Otherwise, an appropriate class loader is called to load and link the named class. In other words, if a Java program directly calls the machine code generated by the C/C ++ language, the security of this part of the code is controlled by the Java Virtual Machine.
JNI implementation steps
The general process for compiling JNI code is shown in:
JNI implementation flowchart
1. First write the Java class source files that require the JNI function. The methods that require JNI implementation should be declared with the native keyword. In this class, use the system. loadlibrary () method to load the required dynamic link library. The key code is as follows:
// Compute. Java
......
Public class compute {
Public native double comp (double [] Params );
......
Static {
// Call the dynamic link library
System. loadlibrary ("mathlib ");
}
......
}
2. Compile the class source file into a binary bytecode file using the Java class compiler. Because native keyword declaration is adopted, the compiler ignores the JNI method without code bodies.
3. Use javah-JNI *. Class to generate the header file of the relevant JNI method. You can manually generate the file. However, because the Java Virtual Machine calls the JNI method according to certain naming rules, you must be very careful when writing the header file manually.
Some code of the header file generated by the above file is as follows:
// Compute. h
......
Extern "C "{
Jniexport jdouble jnicall java_compute_comp (jnienv *, jobject, jdoublearray );
}
......
It can be seen that the JNI function name is divided into three parts: the first is the Java keyword for Java Virtual Machine recognition; the second is the caller Class Name (fully qualified class name, where the name separator is replaced by an underscore ); finally, it is the corresponding method name, which is separated by underscores.
The parameters of the JNI function are also composed of three parts: jnienv *, which is a pointer to the JNI runtime environment; the second parameter varies with whether the local method is static or non-static. The second parameter of the non-static local method is an object reference, the second parameter of the static local method is a reference to its Java class. Other parameters correspond to common Java method parameters, and the parameter types need to be mapped according to certain rules.
4. Compile the implementation code of the corresponding method based on the header file. Due to space limitations, the specific implementation part will not be described here. During the encoding process, you must pay attention to the length of variables. For example, if the length of an integer variable in Java is 32 bits and that of a C language is 16 bits, you must carefully check the variable type ing table, prevents problems during value transfer.
5. Use the C/C ++ compiler to compile the JNI implementation code into a dynamic link library. The Linked Library must be explicitly called in the caller class.
In the Win32 environment, you can use visual c ++ or other C/C ++ compilers that can generate DLL files to compile the code into a dynamic link library. I am using the Microsoft. NET Framework compiler. The compilation command is as follows, where % java_home % is the author's JDK installation directory variable:
CL-I % java_home %/include
-I % java_home %/include/Win32
-LD jnicmp. C-femathlib. dll
In Sun soloaris, the corresponding command is:
CC-g-I/usr/local/Java/include/Solaris jnicmp. c/
-O mathlib. So
Note: during compilation, you must use the I command to include the necessary library file path.
After the above processing, the development of a Java class containing the localization method is basically completed.
Application of JNI technology
Most of the major Java technologies, such as JDBC and RMI, are implemented in JNI mode. However, using JNI does affect the platform independence of the program, so it can only be used where it is needed. In general, if we encounter the following situations, we can consider JNI:
● You need to directly operate the physical device without related drivers. In this case, you may need to use C or even assembly language to compile the driver of the device and then call it through JNI;
● A large amount of data ** computing is involved. Using java will cause some efficiency loss;
● Using Java will produce overhead that is hard to pay by the system, such as when a large number of network connections are required;
● There are a large number of reusable C/C ++ code. Using JNI can reduce the development workload and avoid repeated development.
In addition, pay attention to the following points when using JNI technology:
● Due to restrictions of the Java security mechanism, do not try to publish the applet containing the localization method to the client using the JAR file;
● Pay attention to the memory management issue. Although local references are automatically released after the local method returns Java, too many local references will exhaust the memory when the VM executes the local method;
● The JNI technology not only allows Java programs to call C/C ++ code, but also allows C/C ++ code to call Java code.