(Linux/CentOS/Solaris) How to Load a Java Native/Shared Library (.so)

There are several ways to make it possible for the Java runtime to find and load a native shared library (.so) at runtime. I will list them briefly here, followed by examples with more explanation below.

  1. Call System.load to load the .so from an explicitly specified absolute path.
  2. Copy the shared library to one of the paths already listed in java.library.path
  3. Modify the LD_LIBRARY_PATH environment variable to include the directory where the shared library is located.
  4. Specify the java.library.path on the command line by using the -D option.

Note: To help resolve an UnsatisfiedLinkError Runtime Error, see How to Handle the UnsatisfiedLinkError Runtime Error in Java

1. Call System.load to load the shared library from an explicitly specified absolute path.

This choice removes all uncertainty, but embeds a hard-coded path within your Java application. Example:

import com.chilkatsoft.CkZip;

public class Test {
	
  static {
    try {
    	System.load("/home/joe/chilkatJava/libchilkat.so");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[]) 
  {
    CkZip zip = new CkZip();
    System.out.println(zip.version());    
  }
}

2. Copy the shared library to one of the paths already listed in java.library.path

To view the paths listed in java.library.path, run this Java code:

String property = System.getProperty("java.library.path");
StringTokenizer parser = new StringTokenizer(property, ";");
while (parser.hasMoreTokens()) {
    System.err.println(parser.nextToken());
    }

Note: The java.library.path is initialized from the LD_LIBRARY_PATH environment variable.

The loadLibrary method may be used when the directory containing the shared library is in java.library.path. To load "libchilkat.so", call System.loadLibrary("chilkat"), as shown below.

import com.chilkatsoft.CkZip;

public class Test {
	
  static {
    try {
    	
    	System.loadLibrary("chilkat");
    	
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }
	
  public static void main(String argv[])
  	{
    CkZip zip = new CkZip();
    System.out.println(zip.version());
	}
  }

3. Modify the LD_LIBRARY_PATH environment variable to include the path where the Chilkat shared library is located.

For Bourne Shell, K Shell or Bash, type:

export LD_LIBRARY_PATH=/home/joe/chilkatJava-9.1.1-x86_64-linux:$LD_LIBRARY_PATH

For C Shell, type:

setenv LD_LIBRARY_PATH "/home/joe/chilkatJava-9.1.1-x86_64-linux:$LD_LIBRARY_PATH"

4. Specify the java.library.path on the command line by using the -D option.

For example:

java -Djava.library.path=".:/home/joe/chilkatJava-9.1.1-x86_64-linux" TestApp