2012-06-20

Java memory options

On a 32-bit Windows 7 machine running Oracle JDK 7, the default Java heap size is around 256M.

The JVM memory settings are the following:
-Xms        set initial Java heap size
-Xmx        set maximum Java heap size
-Xss        set java thread stack size

This means that we can change the initial and maximum heap size using:

java -Xms512M -Xmx1G MyMainClass

M stands for MegaByte and G for GigaByte.
There is also a "standard" way of defining these parameters using the JAVA_OPTS environment variable:

SET JAVA_OPTS=-Xms1G -Xmx1G

For instance, execution scripts created using gradle install will apply the options specified in JAVA_OPTS and in an application-specific variable (e.g. MY_APP_OPTS).

This in practice, does:

java %JAVA_OPTS% MyMainClass


The following Java program can query the memory using the Runtime object.

// credits: mike http://stackoverflow.com/a/7019624
public class MyMainClass {

    public static void main(String[] args) {
        Runtime rt = Runtime.getRuntime();
        long totalMem = rt.totalMemory();
        long maxMem = rt.maxMemory();
        long freeMem = rt.freeMemory();
        double megs = 1048576.0;

        System.out.println ("Total Memory: " + totalMem + 
" (" + (totalMem/megs) + " MiB)");
        System.out.println ("Max Memory:   " + maxMem +
" (" + (maxMem/megs) + " MiB)");
        System.out.println ("Free Memory:  " + freeMem + 
" (" + (freeMem/megs) + " MiB)");
    }

}

No comments: