Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read maximum heap space at runtime

As we all know, the java -Xmx option is used to set the maximum heap space available to a Java program. But is there a way for a Java program to read the value that has been set? Something like System.getMaximumHeapSpace() (which does not exist).

like image 937
D-Bug Avatar asked Jun 14 '09 15:06

D-Bug


People also ask

How do I get heapSize in Java?

// Get current size of heap in bytes long heapSize = Runtime. getRuntime(). totalMemory(); // Get maximum size of heap in bytes.

What is my maximum heap size?

Maximum heap size is 1/4th of the computer's physical memory or 1 GB (whichever is smaller) by default. The maximum heap size can be overridden using -Xmx.

How do I monitor my heap size?

The easy way to monitor Heap usage is by using a commercial APM (Application Performance management tool) such as CA Wily APM, AppDynamics, New Relic, Riverbed, etc. APM tools not only monitor the heap usage, but you can also configure the tool to Alert you when Heap usage is not normal.


1 Answers

There is a Runtime.maxMemory, which the documentation says will return the maximum amount of memory the Java Virtual Machine will attempt to use, but it is not specific whether it is the maximum heap memory set when launching the JVM.

Just as a test, I wrote the following program:

class MaxMemory {
    public static void main(String[] args) {
        System.out.println(Runtime.getRuntime().maxMemory());
    }
}

The results of the execution was the following:

C:\coobird\>java -Xmx64m MaxMemory
66650112

C:\coobird\>java -Xmx128m MaxMemory
133234688

This is using Java SE 6 version 1.6.0_12 on Windows.

Although the values are close to 64 MB (67,108,864 bytes) and 128 MB (134,217,728 bytes), they aren't exactly so.

like image 119
coobird Avatar answered Sep 30 '22 15:09

coobird