This application demonstrates basic usages of Java Native Interface (JNI).
There are three usages in this demo.
The hello world application implementation is resides in the jni-hello module. It uses javac compiler and g++ compiler to compile the project and run. Main class of this module calls native library native.dll to print "hello world".
JDK includes tools to generate header files for the native method interface.
in java 8 and prior using javah command and _java -h_in java 9 and higher.
Native library should be included in the java.library.path to link the library at the run time. Java path is defaulted to system PATH variable if not explicitly set.
This demo can be run using script-run.bat
- Run
cd /jni-hello
- Run
./script-run.bat
from cmd
MD5 hash code generate example using C native code to execute hashing algorithm. This example uses maven to compile the project.
org.codehaus.mojo
native-maven-plugin
native maven plugin has been used to compile the native library. Since it internally uses the g++/gcc compiler
g++/gcc installation is a requirement to this plugin. Native library implementation resides in the c-hash module and java code resides in the java-hash module.
javah goal in the maven plugin (above mentioned) has been used to generate the header files of the native code.
This project bundles native library into the jar file generated. DLLLoader
class is used to extract native library from jar to directory jar is located
since Java doesn't provide a mechanism to load a native library from the jar itself.
Note: Currently as the name implies this class supports dll extension in windows environment only. Can be modified to extract linux
.so
files with minimal set of changes.
- Run
mvn clean install
from the project root - Run
cd /java-hash
- Run
./script-run.bat
from cmd
Cache implementation to store java objects in native memory. Like the hash generator this uses same maven plugin to build the project.
Cache is implemented in C++ using a map and can be stores the jobject
as a global reference.
Native memory cache implementation is an important topic in the java ecosystem since on heap cache increases the heap size and can be a cause for long GC cycles. Since the native memory management is done manually this resolves that problem.
- Run
mvn clean install
from the project root - Run
cd java-cache-caller
- Run
./script-run.bat
from cmd
- JDK 8 or higher
- maven installation
- This project supports only
dll
libraries and windows environment, but easily can be modified to be used in the linux environment. - g++/gcc compiler
In windows environment mingw can be used to compile c/c++ programs. mingw-w64 for 64bit envirnment or mingw for 32bit environment
In linux environment to install run
sudo apt install gcc
sudo apt install g++