How to dispose library loaded with JNA

萝らか妹 提交于 2019-12-06 11:45:40

问题


I'm using JNA to load a native Library using:

MyLibrary INSTANCE = (MyLibrary) Native.loadLibrary("mylibrary.so", MyLibrary.class);

Now I want to clean up and dispose the library. I've read about the dispose method but this is defined on the class NativeLibrary, how I am supposed to call this?

Anyway, is it necessary to do that? I'm using jna with Apache Spark on a large scale, so I'm loading the library thousand of times, I'm wondering of there are any resources left open if I do nit excplicitly call dispose?

EDIT: I've seen the question Jna, Unload Dll from java class dynamically, but it does not provide a solution to my problem.

There is no accepted answer. People suggest to call NativeLibrary.dispose(), but there is no such static method in NativeLibrary. If I try to cast my library instance (which is of type Library), then I get a class-cast exception.


回答1:


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 that the object will be collected, but by setting INSTANCE to null, you allow the system to reclaim its resources. (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 were 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: Use 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 after disposing to ensure the native OS releases its reference as well.



来源:https://stackoverflow.com/questions/41056322/how-to-dispose-library-loaded-with-jna

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!