Question

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.

Was it helpful?

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.

OTHER TIPS

I have written an extensive JNI layer for the iSeries to access DB2, user queues, data queues and a few other OS/400 specifics. Much of our system on the iSeries would have been impossible without JNI. So, yes, JNI has it's place, and when you need it, you really need it.

It's relatively difficult (next to pure Java), but powerful and not horrible.

Also, whenever I am looking at some JNI code, I also consider using JNA.

I can think of a few uses off the top of my head:

  1. integration with existing low-level (C/C++) APIs that do not have a Java counterpart
  2. integrating with aspects of the system that are not exposed through available Java APIs (direct hardware access, etc.)

Some might say it can be useful for creating highly-optimized sections of code however with modern JVMs you're getting pretty fast and the complications of using JNI would probably outweigh any performance benefit you might see.

There are a few uses for binding to FFMPeg for C-decoding of (damn near any) video/audio format.

There's also JNA, which makes it like you are using the library itself. This is "easier" from the standpoint that it passes everything to the Java developer to manage, and harder in the sense that you have to figure out the structure mapping and do a lot of grunt work to get all the pointers, etc, to pass correctly.

We had an requirement to wrap a new UI around a legacy C application running on Suse Linux. JNI was the perfect tool for the Job.

In general I think JNI is a contradiction to the Java notion of Write Once, Run Anywhere. However there are use cases where JNI can be useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top