使用java.library.path和LD_LIBRARY_PATH之间的区别

chr*_*ian 16 java linux java-native-interface shared-libraries

设置JVM参数之间是否存在差异

-Djava.library.path=/path 
Run Code Online (Sandbox Code Playgroud)

在JVM启动并设置Linux环境变量

export LD_LIBRARY_PATH=/path 
Run Code Online (Sandbox Code Playgroud)

在JVM启动之前?

这两种方法有哪些优点/缺点?

ali*_*dro 15

第一种形式

-Djava.library.path=/path
Run Code Online (Sandbox Code Playgroud)

将在java字节码级别处理,System.loadLibrary将调用Runtime.loadLibary,然后将调用java/lang/ClassLoader.loadLibrary.在函数调用中ClassLoader.loadLibrary,java.library.path将检查系统属性以获取库的完整路径,并将此完整路径传递给本机代码以调用系统api dlopen/dlsym,最终使库加载.您可以从OpenJDK存储库浏览源代码.以下代码段是我从链接中复制的段.

此表单的优点是,如果库路径存在一些问题,您将在Java代码中收到错误或警告或异常.

// Invoked in the java.lang.Runtime class to implement load and loadLibrary.
static void loadLibrary(Class fromClass, String name,
                        boolean isAbsolute) {
    ClassLoader loader =
        (fromClass == null) ? null : fromClass.getClassLoader();
    if (sys_paths == null) {
        usr_paths = initializePath("java.library.path");
        sys_paths = initializePath("sun.boot.library.path");
    }
    if (isAbsolute) {
        if (loadLibrary0(fromClass, new File(name))) {
            return;
        }
        throw new UnsatisfiedLinkError("Can't load library: " + name);
    }
// ....
Run Code Online (Sandbox Code Playgroud)

第二种形式

export LD_LIBRARY_PATH=/path
Run Code Online (Sandbox Code Playgroud)

根据文件,将以原生方式处理 dlopen/dlsym

 dlopen()
   The function dlopen() loads the dynamic library file named by the null-terminated string filename and returns an opaque  "handle"  for  the
   dynamic  library.   If  filename is NULL, then the returned handle is for the main program.  If filename contains a slash ("/"), then it is
   interpreted as a (relative or absolute) pathname.  Otherwise, the dynamic linker searches for the library as follows (see ld.so(8) for fur?
   ther details):

   o   (ELF  only)  If  the  executable  file for the calling program contains a DT_RPATH tag, and does not contain a DT_RUNPATH tag, then the
       directories listed in the DT_RPATH tag are searched.

   o   If, at the time that the program was started, the environment variable LD_LIBRARY_PATH was defined to contain a colon-separated list of
       directories, then these are searched.  (As a security measure this variable is ignored for set-user-ID and set-group-ID programs.)
Run Code Online (Sandbox Code Playgroud)

以这种方式,如果您的库路径存在一些问题,并且系统无法加载您的库,系统将不会给出太多线索会发生什么,并且会无声地失败(我猜).这取决于是否实现LD_LIBRARY_PATH,Android没有LD_LIBRARY_PATH用来确定库的位置,你可以从这里看到Android的实现.

  • 值得注意的是(但正如您可能从这种差异中预料到的那样),加载引用其他库的本机库(ala -lboost 或其他)_不会_ 在 `java.library.path` 中找到引用的库,但_会_ 在 `$LD_LIBRARY_PATH` 中找到它们。 (3认同)

chr*_*ian 5

Java 可以显式加载列出的库, -Djava.library.path=... 如 alijandro 所描述的那样。

例如,如果在绑定模式下使用 mq 系列,则可以指定所需库的路径, -Djava.library.path=/opt/mq/java/lib然后 mqseries 加载库。

如果一个库不是从java显式加载的,即必须使用一个依赖库,那么LD_LIBRARY_PATH必须使用该库才能在jvm中可用。