Java JNI call to load library

Does this affect memory if I have two Java classes that have their own calls to compiled C code, and I call both of these classes in another class? For example, I have class A and class B with both calls to my own functions. They are configured as follows:

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; } } 

Then class C calls both, since they both make a static call to load the library, what does it matter in class C? Or is it better if class C calls 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(); } } 
+7
source share
4 answers

No, that doesn't matter. It is safe to call loadLibrary () more than once in the same class loader.

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. 
+7
source

It is better to have a class that uses a library, load the library. If you need to load a library, you can call your own methods without loading the library.

+1
source

Jni libs are dynamic libraries. I think they should have been loaded by loadLibrary. One of the advantages of dynamic libraries is that if they are already loaded into memory, this copy is used instead of reloading. This way you can use two loadlibrary calls.

Another problem is that if you put the loadlibrary call in class C, you mess up the encapsulation of the other two classes. In any large project, someone will eventually call one of the internal calls of class a or class b without going through class c. This will not work so well.

+1
source

It seems that the NdkFoo class would be reasonable, and each method would be native. Then from A you can use

 NdkFoo.getInstance().mathMethod(); 

and B could do

 NdkFoo.getInstance().nonMathMethod(); 

It also creates a native library name that matches the name of the java support class.

0
source

All Articles