[JAVA] Item 66: Use native methods judiciously
66. Native methods should be used with caution
native method
You can call methods written in C or C ++ using the Java Native Interface (JNI).
Historically, native methods have three uses.
- To access platform-specific features such as the windows registry
- To use a library of native code, including a library to access legacy data
- To improve performance
It is legitimate to use native methods to access platform-specific features.
That said, Java has matured, so it has most of its features. For example, Java 9 allows you to access OS processes.
Also, if there is a library in the native library that is not in Java, you can use the native method.
I rarely use native methods for performance.
It seems that such a thing happened in early Java, but the performance has not changed so much due to the evolution of the JVM.
Disadvantages of native methods
The native method has major drawbacks.
- Since native methods are not safe (I think it is memory management safety in the sense that BOF does not occur) (Item50), applications using native methods are Java, but memory corruption errors. It cannot be said that there is immunity to.
- native methods are platform dependent and therefore not portable.
- Difficult to debug
- If you are not good at it, the performance will deteriorate. Garbage collectors can go wrong, and the cost of going back and forth between native code is high.
- Requires glue code that is not readable and requires redundant description.
In other words, think carefully and use the native method.