简体   繁体   中英

What is the real world application of Java Native Interface?

我已经成功地使用 JNI 执行了一个简单的程序,我知道 JNI 是什么但我想知道它在哪里实时使用以及为什么我们需要 JNI 而我们可以在 Java 中做任何事情。

... while we can do anything in java

That's the flaw in your thinking. There some things that you cannot do in Java. There are other things that you cannot do efficiently in Java.

Examples include:

  • interacting with OS functions in ways that the Java APIs don't support,
  • calling libraries implemented in other programming languages, and
  • interacting with memory-mapped devices.

An important application of JNI is to wrap existing libraries; the alternative would be to port huge projects (with the cost associated with writing the new code and testing).

See in example QuantLib, https://www.quantlib.org . They port the whole library to Java with SWIG, which in turn uses JNI.

I will add one real life use case here. Our software application connects to different vendors to get data from them. For this we use vendor supplied api's. 2 of our vendors only have C/C++ API's and since our application is in Java we use JNI to communicate with these API's.

Although JNI is quite brittle to use but if it did not exist it would mean we would have to rewrite parts of our application in C++ which would be tens of thousands of lines of code + the maintenance cost of maintaining code bases in 2 different languages.

One possible way to avoid JNI in our situation is to have messaging middleware that could be used for communications between Java and C++ process's but then we have latency issues + configuration and maintenance of another complex piece of software to deal with.

Although I haven't used JNI lately but about 6 or 7 years ago, I was working on a Java application where we were implementing cryptography. I implemented some of the cryptographic algorithms in C to improve their performance and used JNI as a wrapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM