I\'m using JNA to load a native Library using:
MyLibrary INSTANCE = (MyLibrary) Native.loadLibrary(\"mylibrary.so\", MyLibrary.class);
Now
Your post implies that you are concerned primarily with resource consumption. This is not a concern for loading it "thousands of times" -- it is much like a static variable, once loaded it is not reloaded.
If you do want to unload it, you essentially have three options.
Option 1:
INSTANCE = null;
System.gc(); // or simply wait for the system to do this
There are no guarantees when (if ever) the object will be collected, but by setting INSTANCE
to null, you allow the system to reclaim its resources when it wants to. (The dispose()
method is called as part of the object's finalize()
method, so it gets disposed when the object is eventually collected.) If you're really done with the instance, this may be sufficient for you. Note this should not be relied on in cases where reloading the library is necessary for other behavior, as garbage collection is not guaranteed.
Option 2:
INSTANCE = null;
NativeLibrary lib = NativeLibrary.getInstance("mylibrary.so");
lib.dispose();
This will explicitly dispose of the native library, and would be the preferred method if you need to reload the library to force programmatic behavior on reloading (as opposed to reusing the existing instance.) Note if you used options when loading the library you need to use those same options with this call as well.
Option 3:
NativeLibrary.disposeAll();
This unloads all your libraries. Depending on how many other libraries you use (which will have to be reloaded when used again) this may work for you.
Note that in all these options you may want a small time delay of a few milliseconds after disposing, to ensure the native OS does not return the same handle.