The difference between System.load and System.loadLibrary in Java

  sonic0002        2019-02-05 05:49:28       26,850        1    

When writing code using native library in Java, normally the first step is loading some native library.

static{
  System.load("D:" + File.separator + "Hello.dll");
}

JDK provides two ways to load libraries:

  • System.load(String filename)
  • System.loadLibrary(String libname)

This post will try to explain the differences of these two ways.

According to Java Doc on System.load(), it has below description.

Loads the native library specified by the filename argument. The filename argument must be an absolute path name.

The parameter of this method should be an absolute file path with the extension name.

According to Java Doc on System.loadLibrary(), it has below description:

Loads the native library specified by the libname argument. The libname argument must not contain any platform specific prefix, file extension or path.

The library normally would be loaded from system library path. What is system library path? Let's take an example, we have below code to load a library.

static{
    System.loadLibrary("Hello");
}

The output is:

The exception says it cannot find the library Hello in java.library.path, let's find out what is the java.library.path? 

public static void main(String[] args){
    System.out.println(System.getProperty("java.library.path"));
}

It will print a list of paths in the system. You just need to put the lib under any path printed in the above statement.

Another difference between these is related to dependency between native libraries. Let's assume there are two native libraries A.dll and B.dll and A.dll is statically linked to B.dll,  if using System.load("D:/A.dll"),  it would throw exception even if B.dll is under the same directory as A.dll. In this case, JVM finds that A.ddl depends on B.dll when trying to load A.dll, it will try to find B.dll under java.library.path but B.dll is not found.

There two solutions for this

  1. Call System.load("D:/B.dll"), then call System.load("D:/A.dll")
  2. Put A.dll and B.dll under java.library.path and then call System.loadLibrary("A")

JAVA  JNI  NATIVE  SYSTEM.LOAD  SYSTEM.LOADLIBRARY 

       

  RELATED


  1 COMMENT


Anonymous [Reply]@ 2020-06-29 22:19:04

I think that there is minor wrong in "There two solutions for this:". The #2 is wrong. The other needed DLL despite located in java.library.path still errors. The solution, I found is instead to set the PATH environment variable to where the other DLL is. I tested this both in Windows and Linux. It is the PATH that must be set in order that the other DLL is to be found. Else, it is never found even if it is beside. Please rectify.



  RANDOM FUN

Texting in class

How to send SMS safely in class. New skill get