Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the max object size if max heap size is known?

Tags:

java

I ran this test with -Xmx256M to determine the max object size that I can create on heap

    for (int m = 128;; m++) {
        try {
            byte[] a = new byte[m * 1024 * 1024];
        } catch (OutOfMemoryError e) {
            System.out.println(m + "M");
            break;
        }
    }

and got 171M. Is there a way to calculate this size?

like image 873
Evgeniy Dorofeev Avatar asked Apr 27 '13 03:04

Evgeniy Dorofeev


People also ask

How can we find the actual size of an object on the heap?

One way to get an estimate of an object's size in Java is to use getObjectSize(Object) method of the Instrumentation interface introduced in Java 5. As we could see in Javadoc documentation, the method provides “implementation-specific approximation” of the specified object's size.

What happens if you specify max heap size greater than available RAM?

If your -Xmx (maximum) is larger than the available memory (total memory to include any virtual memory) you will get a runtime failure if and only if your JVM processes actually tries to use more memory than the machine has.

What is my maximum heap size?

The default maximum Java heap size is 256 MB.

How do I check my Java heap size?

Open a terminal window. Review the command output. The argument beginning with "-Xmx" will give you the value of the current Java heap space. In the example above, the value is 1024 MB, or 1 GB.


1 Answers

Is there a way to calculate this size?

No. The maximum allocatable object size depends on the amount of contiguous free space available in the heap. AFAIK, there's no practical way of finding out what that might be ... apart from doing what you are currently doing.

like image 155
Stephen C Avatar answered Nov 15 '22 01:11

Stephen C