JNI and non-modal JWindow created from C++
I have the following situation in my application:
My main application is a Visual C++ GUI application. In this application the user has the option to open a non-modal Java Swing window. To do the communication between C++ and Java I use JNI. Since I only have to perform some basic communication between the C++ and the Java code I have written a Java class which extends JWindow and which has a static method which I call from my C++ code using JNI. This static Java method just creates the non-modal JWindow and shows it. The main problem I have now is that my C++ never gets a message when the user closes the Java window. So I never have the chance to close theVM created by JNI if I don't need it any more. Since the Java window allocates very much heap memory during runtime my C++ blows up because the VM reserves so much memory.
So my question is: is there an easy way to let my C++ code know when the Java window is closed so that I can destroy the VM? As far as I know the "standard Java VM" is shut down if the last displayable window in Java is disposed. But I think this won't work for JNI, because I have to destroy the VM myself?
Any answers and hints welcome.
[1202 byte] By [
J-Braina] at [2007-11-26 20:16:36]

# 2
I already use the -Xmx Option to increase the max. heap size of the VM. That is not the problem. The problem is that as long as the window is shown and not closed by the user the VM exists and my application allocates the maximum heap size but it may no longer need it, because the operation which uses the memory is already done.
I thought that if I create a VM using JNI_CreateJavaVM I can destroy it using DestroyJavaVM. But I just read some posts and statements where it is said that DestroyJavaVM may not work.
# 3
Xmx is the maximum. That doesn't mean it allocates it all. It only allocates it if you have references that use all of it or if you set the minimum.
I am rather certain that you can create a timer which will time out the window allowing you to close it automatically if the user hasn't interacted with it in a while.
However that still won't help destroying the VM.
# 4
My application needs all the memory, so after the user has started a process in the Java window, the VM nearly has used all of the memory. Since after the process all objects which have been allocated on the heap are no longer reference the garbage collector frees them. But the allocated heap is still at maximum (I can see it using the Windows Task manager).
My workaround for the problem is to call System.gc() three times after the process has finished, so the garbage collector compacts the unused heap memory nearly to the -xms value. It's not a good solution, but it works.