代码改变世界

Effective Java 54 Use native methods judiciously

2014-04-17 20:29  小郝(Kaibo Hao)  阅读(391)  评论(0编辑  收藏  举报

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

Historical usages of native methods

  1. Access to platform-specific facilities such as registries and file locks.
  2. Access to libraries of legacy code.
  3. Access to native methods written for performance-critical part of application.

Disadvantage of native methods

  1. Native language are not safe (Item 39), native methods are no longer immune to memory corruption errors.
  2. Since native languages are platform dependent, application use them are far less possible.
  3. Difficult to debug.
  4. Fixed cost associated with going into and out of native code.
  5. It requires "glue code" that is difficult to read and tedious to write.

Summary

Think twice before using native methods. Rarely, if ever, use them for improved performance. If you must use native methods to access low-level resources or legacy libraries, use as little native code as possible and test it thoroughly. A single bug in the native code can corrupt your entire application.