Java JNI call to load library

JPM picture JPM · Dec 8, 2011 · Viewed 14.1k times · Source

Does it impact memory if I have two Java classes that have native calls to compiled C code and I call both those classes in another class? For instance I have Class A and Class B with both calls to native functions. They are setup like this:

public class A{
    // declare the native code function - must match ndkfoo.c
    static {
        System.loadLibrary("ndkfoo");
    }

    private static native double mathMethod();

    public A() {}

    public double getMath() {
          double dResult = 0;  
          dResult = mathMethod();
          return dResult;
    }
}


public class B{
    // declare the native code function - must match ndkfoo.c
    static {
        System.loadLibrary("ndkfoo");
    }

    private static native double nonMathMethod();

    public B() {}

    public double getNonMath() {
          double dResult = 0;  
          dResult = nonMathMethod();
          return dResult;
    }
}

Class C then calls both, since they both make a static call to load the library will that matter in class C? Or is it better to have Class C call System.loadLibrary(...?

public class C{
    // declare the native code function - must match ndkfoo.c
    //  So is it beter to declare loadLibrary here than in each individual class?
    //static {
    //  System.loadLibrary("ndkfoo");
    //}
    //

    public C() {}

    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        double result = a.getMath() + b.getNonMath();

    }
}

Answer

Andy Thomas picture Andy Thomas · Dec 8, 2011

No, it doesn't matter. It's harmless to call loadLibrary() more than once in the same classloader.

From the documentation for Runtime.loadLibrary(String), which is called by System.loadLibrary(String):

   If this method is called more than once with the same library name, 
   the second and subsequent calls are ignored.