Hi all,
I have a question regarding the JVM memory management (at least for the SUN's one).
I would like to know how to control the fact that the JVM send the unused memory back to the OS (windows in my case).
I wrote a simple java program to illustrate what I expect. Run it with -Dcom.sun.management.jmxremote option so that you can also monitor the heap with jconsole for example.
With the following program:
package fr.brouillard.jvm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
public class MemoryFree {
private BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
private List<byte[]> usedMemory = new LinkedList<byte[]>();
private int totalMB = 0;
private int gcTimes = 0;
public void allocate(int howManyMB) {
usedMemory.add(new byte[howManyMB * 1024 * 1024]);
totalMB += howManyMB;
System.out.println(howManyMB + "MB allocated, total allocated: " +
totalMB + "MB");
}
public void free() {
usedMemory.clear();
}
public void gc() {
System.gc();
System.out.println("GC " + (++gcTimes) + " times" );
}
public void waitAnswer(String msg) {
System.out.println("Press [enter]" + ((msg==null)?"":msg));
try {
reader.readLine();
} catch (IOException e) {
}
}
public static void main(String[] args) {
MemoryFree mf = new MemoryFree();
mf.waitAnswer(" to allocate memory");
mf.allocate(20);
mf.allocate(10);
mf.allocate(15);
mf.waitAnswer(" to free memory");
mf.free();
mf.waitAnswer(" to GC");
mf.gc();
mf.waitAnswer(" to GC");
mf.gc();
mf.waitAnswer(" to GC");
mf.gc();
mf.waitAnswer(" to GC");
mf.gc();
mf.waitAnswer(" to exit the program");
try {
mf.reader.close();
} catch (IOException e) {}
}
}
The internal heap is free once the first GC is done (what is expected) but the memory is only sent back to the OS starting from the third GC. After the fourth, the full allocated memory is sent back to the OS.
How to setup the JVM to control this behaviour? In fact my problem is that I need to run several CITRIX clients sessions on a server, but I would like the running JVMs on the server to free the memory as soon as possible (I have only few high consuming memory functions in my application).
If this behaviour cannot be controlled, can I let it like this and increase instead the OS virtual memory and let the OS using it as it wants without big performance issues. For example, would there be issues to have 10 java process of 1GB memory (with only 100MB real allocated objects in the heap) on a 4GB server with enough virtual memory of course.
I guess that other people already faced such questions/problems.
Thanks for your help.