Determining Heap Size

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

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);  }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS