Can someone explain the whys and the wherefores for using native keyword in Java?
Can someone explain the whys and the wherefores for using native keyword in Java?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In my experience, the downsides of using native code libraries are significant:
JNI / JNA have a tendency to destabilize the JVM, especially if you try to do something complicated. If your native code gets native code memory management wrong, there’s a chance that you will crash the JVM. If your native code is non-reentrant and gets called from more than one Java thread, bad things will happen … sporadically. And so on.
Java with native code is harder to debug than pure Java or pure C/C++.
Native code can introduce significant platform dependencies / issues for an otherwise platform independent Java app.
Native code requires a separate build framework, and that may have platform / portability issues as well.
Generally speaking, you don’t gain much (if any) extra performance by using native code. While you might think your C/C++ will be more performant than Java, the JIT compiler does a pretty good job of optimizing these days, and you have to consider the performance costs of making JNI calls and other interactions across the JNI boundary.
Generally specking, you should treat JNI / JNA as a “last resort” option. If there is any other way of solving the problem, that way is probably better.