Item 54 - Use native methods judiciously

From Effective Java 2/e by Joshua Bloch

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++.

Three main usage

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

It is rarely advisable to use native methods for improved performance

  1. For most tasks, it is now possible to obtain comparable perfor- mance without resorting to native methods
  2. Because native languages are not safe, applications using native methods are no longer immune to memory corruption errors
  3. Because native languages are platform dependent, applications using native methods are far less portable
  4. Applications using native code are far more difficult to debug
  5. 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
  6. Native methods require “glue code” that is difficult to read and tedious to write

Posted by The Finest Artist