Search code examples
javainteropjava-native-interface

Usefulness of JNI


I've been a java developer for a couple years and have heard that you can do some pretty useful and powerful things with JNI. I don't know if I just haven't needed to use it or if it isn't terribly relevant to me; but I have not had to touch it at all.

I am wondering what the usefulness of this aspect of Java is. Examples would be great.


Solution

  • It is very useful. I can see 2 primary reasons to use JNI (there are likely more).

    1. Performance. If you have a piece of code in which the Java Runtime for whatever reason can't cut it performance wise. You can implement that function in native code and call it from Java. This allows you to hand tune the implementation if you really need to. This is likely the least common reason though, Java usually performs just fine.

    2. Access to OS Specific APIs. This one is a biggie. I've had a case where I needed to do something in Java but also needed access to something that Java simply could not provide. In my case it was UNIX domain sockets. Since (as you can tell by the name) they are UNIX specific, there is no standard Java way to use them. So I made a class that acted like a wrapper around them in C and accessed it with JNI. viola, problem solved.