Search code examples
javadlljarjava-native-interface

Why changing name of jar causes UnsatisfiedLinkError exception


Why does same jar contents with name shaded.jar fail to load dll while with name sigar.jar , dlls load successfully?

I am using shaded jar in maven.It creates a jar: shaded.jar.

I have an artifact :

<dependency>

        <groupId>org.hyperic</groupId>

        <artifactId>sigar</artifactId>

        <version>1.6.5.132-7</version>

    </dependency

I use it in my code like:

SigarProxyCache.newInstance(new Sigar(), 100).getPid();

Since this jar uses dll, I have kept all the dlls in the same folder as shaded.jar, but still i get following exception:

Caused by: org.hyperic.sigar.SigarException: java.lang.UnsatisfiedLinkError: org.hyperic.sigar.Sigar.getPid()J at org.hyperic.sigar.SigarProxyCache.invoke(SigarProxyCache.java:220) ... 2 more

If I add sigar.jar (same version that has been added to shaded.jar) to classpath directly instead of packaging it in shaded .jar, no exception is thrown and dll is loaded successfully. (Since jar and lib are in same folder, there wasn't any need to modify the java.library.path)

Furthermore, even if I remove sigar.jar from classpath and rename my shaded.jar(this one contains sigar packaged) to sigar.jar, dll loading is still successful.

Now I have referred following posts:

Extract and load DLL from JAR

UnsatisfiedLinkError: no opencv_java249 in java.library.path

which suggest a solution but my question is, why does changing the name impact dll loading. Since inside shaded.jar as well ass sigar.jar, the package structure is exactly same and in both cases dlls are lying parallel to jar.

Here is list of dll/so files that sigar.jar needs, they all contain sigar in their name: enter image description here


Solution

  • Was curious. Had a look at the code at github. To find the name of the native library they take the class name, search the classpath for a jar file with the same name then look in the directory where it's found. When you put the classes in a file with another name, the jar isn't found, so the same-directory approach fails.