Tuesday, September 4, 2007

Determine the available memory in Java

Java Memory Allocation
The following example shows how much memory that JVM has allocated for your application:

Runtime runtime = Runtime.getRuntime();
System.out.println("allocated memory: " + runtime.totalMemory() / 1024);

The totalMemory() method returns the amount of memory the JVM has allocated from the operating system. Unless you specified the amount of memory to allocate using the -Xms command line option, the totalMemory() method will continually fluctuate as objects are allocated and the garbage collection cleans them up.

The following example shows how to discover how much memory is being used by your application:

Runtime runtime = Runtime.getRuntime();
System.out.println("free memory: " + runtime.freeMemory() / 1024);

The freeMemory() method will return the amount of free memory from the allocated memory. Since this value does not include any memory that hasn't yet been allocated by the JVM, you will need to get a complete picture of the free memory that your application would be able to use. To do this, you need to include the amount of memory that hasn't yet bee allocated by the JVM, but could be allocated if necessary. The following example shows how:

Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
System.out.println("free memory: " + freeMemory / 1024);
System.out.println("allocated memory: " + allocatedMemory / 1024);
System.out.println("max memory: " + maxMemory / 1024);
System.out.println("total free memory: " + (freeMemory + (maxMemory - allocatedMemory)) / 1024);

Sample results from the test below show that Java only allocated a small amount of memory and a large amount of memory is still available to the application:

free memory: 294
total memory: 1984
max memory: 65088
total free memory: 63398

No comments: