Item 54: Use native methods judiciously

1.  The Java Native Interface (JNI) allows Java applications to call native methods, which are special methods written in native programming languages such as C or C++.

 

2.  Native methods have had three main uses. They provided access to platform-specific facilities such as registries and file locks. They provided access to libraries of legacy code, which could in turn provide access to legacy data. Finally, native methods were used to write performance-critical parts of applications in native languages for improved performance.

 

3.  java.util.prefs, added in release 1.4, offers the functionality of a registry, and java.awt.SystemTray, added in release 1.6, offers access to the desktop system tray area.

 

4.  It is rarely advisable to use native methods for improved performance. JVM implementations have gotten much faster. For most tasks, it is now possible to obtain comparable performance without resorting to native methods.

 

5.  The use of native methods has serious disadvantages. Applications using native methods are no longer immune to memory corruption errors. Since native languages are platform dependent, applications using native methods are far less portable. Applications using native code are far more difficult to debug. There is a fixed cost associated with going into and out of native code, so native methods can decrease performance if they do only a small amount of work. Finally, native methods require “glue code” that is difficult to read and tedious to write.

 

你可能感兴趣的:(jni,Native Methods)