devxlogo

Determining Heap Size

Determining Heap Size

Question:
How do I find the size of the heap memory that is available for Java program?

Answer:
The maximum size of the Java heap is fixed by the JVM runtime atstartup, but usually starts from a smaller initial value and graduallygrows to the maximum value as more memory is needed. Both the maximumand initial sizes of the Java heap can be adjusted in most JVMs. Theapproximate size of the heap can be determined withRuntime.totalMemory().

The portion of that memory that is availablefor allocation to new objects is returned by Runtime.freememory().The following example program prints out both the total and freememory sizes, allocates a chunk of memory, and then prints the memorysizes again. If the initial size of your JVM’s heap is about 1 MB, youshould see the total memory increase as the heap grows. The amountof free memory should change as a function of the amount of memoryallocated and the increase in size of the heap.

public final class HeapSize {  public static final int DATA_SIZE = 1024*1024;  public static final void printMemory(Runtime runtime) {    System.out.println("
Total Memory: " + runtime.totalMemory());    System.out.println("Free Memory : " + runtime.freeMemory());  }  public static final void main(String[] args) {    Runtime runtime;    byte[] data;    runtime = Runtime.getRuntime();    printMemory(runtime);    data = new byte[DATA_SIZE];    printMemory(runtime);  }}
See also  5 Tips to Manage a Remote Workforce
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist