6

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275

3 Answers3

3

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

This is interesting, I run the same thing with :

 java -Xmx256M -XX:+AggressiveHeap HeapTest //I hoped this would help

But I constantly get less then with AggressiveHeap.

Eugene
  • 117,005
  • 15
  • 201
  • 306
0

That solution is a bad idea. Any other processes running in the JVM may fail to allocate memory (because this code grabbed it all) and that is likely to cause problems.

System performance may be impaired because processes start disk swapping. Depending on how the JVM works it may do a lot of work to initialise memory that you never access.

You might try:

Runtime.getRuntime().freeMemory()
Runtime.getRuntime().maxMemory()
Runtime.getRuntime().totalMemory()

Refer to the documentation for the limitations of what they return.

Also remember that while you can obtain these values in bytes the size of Java objects is implementation defined and remains obscure.

If you're planning to use this you might also need Instrumentation.getObjectSize() to understand the approximate size of objects. Accessing instrumentation is frankly more trouble than it should be. Here's an answer about how to: In Java, what is the best way to determine the size of an object?

All of these values are guidelines only. They may make sense in a caching strategy in which you want to tune how much space is allocated to a discardable cache but not as exact values for any purpose.

Persixty
  • 8,165
  • 2
  • 13
  • 35