Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JNI call to load library

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();

    }
}
like image 883
JPM Avatar asked Dec 08 '11 20:12

JPM


People also ask

What is a JNI call?

JNI is the Java Native Interface. It defines a way for the bytecode that Android compiles from managed code (written in the Java or Kotlin programming languages) to interact with native code (written in C/C++).

What is Jclass in JNI?

The jclass instance is your object on which a method will be invoked; you'll need to look up the getName method ID on the Class class, then invoke it on the jclass instance using CallObjectMethod to obtain a jstring result. So in short yes, you just call the getName function and look at the jstring result.

What is JNIEnv * env?

jint GetVersion(JNIEnv *env); Returns the version of the native method interface.


2 Answers

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.
like image 149
Andy Thomas Avatar answered Sep 25 '22 07:09

Andy Thomas


Its better to have the class which uses the library, load the library. If you have to caller load the library you make it possible to call the native methods without loading the library.

like image 31
Peter Lawrey Avatar answered Sep 24 '22 07:09

Peter Lawrey