Reliabily unload dll in java
I am trying to unload a dll in java. I have read this and this but it seems that you can not guarantee that the dll will actually be unloaded at a certain time开发者_开发问答. This is because System.gc() simply "asks kindly" for the garbage collector to run.
So here is a break down of the situation. I have a dll that provides some functionality via JNI. Lets call this dll MainDll. MainDll is loaded from a call to System.load("MainDll"). I need to be able to unload and load this dll on the fly.
Is it possible to create another dll that's sole purpose is to load and unload MainDll. Lets call this dll LoaderDll. I could then simple call System.load("LoaderDll") and have some native functions to load and unload MainDll. The reason for doing this, is I have access to functions on the native system that can load and unload the dll on the fly. The tricky part with this is, will I have still be able to access the native functions I have written in MainDll if it loaded from inside LoaderDll.
Sorry if this is a confusing question. It seems its a little difficult to explain.
Thanks
Create a wrapper DLL that does the loading/unloading. Also have wrapper methods in the DLL that turn around and delegate the calls to the loaded MainDll DLL. This way your Java JNI code only knows about a single DLL. It can still request the unload [LoaderDll::unload()] which internally unloads the MainDll.
This should work as long as the methods/functions in LoaderDll can trigger a load of MainDll when they are called when MainDll is not currently loaded, assuming that is the desired behavior instead of throwing an exception/error.
One issue with this would be that LoaderDll would always be loaded.
Add a level of indirection.
Make your native methods call forwarding routines in LoaderDLL. The forwarding routines can use C facilities to forward the calls to code in mainDLL.
If you have a need to dynamically load and unload code, have you considered OSGi. This works in felix at least.
In Oracle/Sun's JDK, System.gc() will trigger a full gc (unless it has been turned off on the command line). It could be just a hint on other JVMs.
Based on your clarifying comments, I think the simplest approach would be to spawn a new JVM, whose sole responsibility is managing your DLL. Probably exposing an RMI interface to access those classes (although a simple stream may be sufficient).
I haven't still encountered a situation where System.gc() not to trigger the garbage collector although it is just a hint. This tutorial actually helped me to do my work: Unload Java JNI DLL
精彩评论