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

使用jvm参数有没有区别?

-Djava.library.path=/path 

在jvm开始

并设置Linuxpathvariables

 export LD_LIBRARY_PATH=/path 

在JVM开始之前。 这两种select有什么优点/缺点?

Solutions Collecting From Web of "使用java.library.path和LD_LIBRARY_PATH之间的区别"

第一种形式

 -Djava.library.path=/path 

将在java字节码级别处理, System.loadLibrary将调用Runtime.loadLibary ,然后将调用java/lang/ClassLoader.loadLibrary 。 在函数调用ClassLoader.loadLibrary ,将检查系统属性java.library.path以获取库的完整路径,并将此完整路径传递给本地代码以调用system 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); } // .... 

第二种形式

 export LD_LIBRARY_PATH=/path 

将根据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.) 

以这种方式,如果你的库路径有问题,系统无法加载你的库,那么系统将不会给出太多的线索,而是会默默地失败(我猜)。 这取决于是否执行LD_LIBRARY_PATH ,Android没有使用LD_LIBRARY_PATH来确定库的位置,您可以从这里看到Android的实现。

Java可以显式加载用alijandro描述的-Djava.library.path=...列出的库。

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

如果一个库没有被明确地从java加载,也就是说必须使用一个从属库,那么必须使用LD_LIBRARY_PATH在jvm中提供该库。