tags:

views:

69

answers:

2

Hi,

I'm working with JNI and trying to unload (destroy) the VM using DestoryJavaVM function (I first call DetachCurrentThread method). It seems like the it has now influence on the VM and it is still up after the call. I read in old Sun posts that DestoryJavaVM had problems in the past (JDK1.1-1.3 in 2001) but I'm using JRE 6 and it probably should work now, right? I need to Load\Unload a VM in the same living process since each loading requires another classes to load. Any ideas how it can be done?

Additional info:

At the unloading phase I can successfully detachCurrentThread and destroyVM (both return JNI_OK). I even FreeLibray (jvm.dll) successfuly (return 1). When I try to Load the JVM again I can LoadLibrary(), then find the CreateVM function in the DLL and the call to CreateVM fails (return -1). What I'm doing wrong here?

Thanks, Guy

+2  A: 

Although it wouldn't answer your question on DestroyJavaVM.

OSGi comes to my mind you could put all classes in a bundle activate it run code and deactivate it, later you use another bundle. See Apache Felix.

Another option less elegant would be to exit the vm and restart it with another classpath.

stacker
+1 Good alternatives.
trashgod
I'm not going to OSGi solution ,sorry. Please see the additional info maybe you can assist.
Guy
+1  A: 

You might check for errant threads. The Invocation API: Unloading the VM mentions, "The VM waits until the current thread is the only non-daemon user thread before it actually unloads." This is required by the Java Language Specification, 12.8.

trashgod
And this can create a problem for a sufficiently complex application where you do not have full control of all the threads (i.e. third-party libraries). I would say it's better to redesign to have the JVM reload the classes (e.g. OSGi). Still, this does likely answer the OP's question.
Kevin Brock
I'm using JRE 1.6 so the Destroy should work. See my additional info I have added to my original post.
Guy
@Guy: You mention that the second call to `JNI_CreateJavaVM()` returns -1. What does `ExceptionOccurred()` say?
trashgod
@trashgod: how can I env->ExceptionOccurred() when the JVM creation failed? the env should be initialized by CreateVM, did I miss something here?
Guy
@trashgod: I can see that the return error code is -1 (JNI_ERR) which is unknown error.
Guy
@Guy: Assuming your first call to `JNI_CreateJavaVM()` succeeds, is anything apparently different in preparing the second call?
trashgod
@trashgod: No, not really. calling the same class/functions again.
Guy
@Guy: Sorry, I'm nonplussed. I get a similar result if I try to invoke `JNI_CreateJavaVM` a second time, but it's no problem to reuse the one that just exited.
trashgod