Java OutOfMemoryError message changes when trying to create arrays of different sizes

In the DKSRathore question How to simulate Out Of Memory: the size of the requested array exceeds the VM limit , some odd behavior was noted when creating the arrays.

When creating an array of size Integer.MAX_VALUE, an exception was thrown with an error java.lang.OutOfMemoryError Requested array size exceeds VM limit.

However, when an array was created with a size less than max, but still above the virtual machine memory limit, an error message is read java.lang.OutOfMemoryError: Java heap space.

Further testing, I was able to narrow the scope of error messages.

long[] l = new long[2147483645];

The exception message reads: "Required array size exceeds VM limit"

long[] l = new long[2147483644];

The exception message reads "Java Heap Space Errors"

- .

- , ?

:

Integer.MAX_VALUE = 2147483647

: , :

int max = Integer.MAX_VALUE;
boolean done = false;
while (!done) {
    try {
        max--;
        // Throws an error
        long[] l = new long[max];
        // Exit if an error is no longer thrown
        done = true;
    } catch (OutOfMemoryError e) {
        if (!e.getMessage().contains("Requested array size exceeds VM limit")) {
            System.out.println("Message changes at " + max);
            done = true;
        }
    }
}
+3
4

JDK 7:

:

if (length > arrayOopDesc::max_array_length(T_ARRAY)) {
  THROW_OOP_0(Universe::out_of_memory_error_array_size());
}

, , max_array_length .

static int32_t max_array_length(BasicType type) {
  assert(type >= 0 && type < T_CONFLICT, "wrong type");
  assert(type2aelembytes[type] != 0, "wrong type");
  // We use max_jint, since object_size is internally represented by an 'int'
  // This gives us an upper bound of max_jint words for the size of the oop.
  int32_t max_words = (max_jint - header_size(type) - 2);
  int elembytes = (type == T_OBJECT) ? T_OBJECT_aelem_bytes : type2aelembytes[type];
  jlong len = ((jlong)max_words * HeapWordSize) / elembytes;
  return (len > max_jint) ? max_jint : (int32_t)len;
}

, - int max - - 2. , , header_size , MAX_VALUE -3

+6

, Java , , ?

+1

,

3.1.3 : VM

VM, , ( API, ) , , . , 512 256 OutOfMemoryError VM. ( ), , , , .

which leads to the conclusion that your heapsize is just suitable for an array of size 2147483644, but not completely free, which leads to the second message. Highlighting more than the result of heapsize results in the first message.

+1
source

After playing with this, I think AndreaG is probably right. Language designers probably chose a relatively large number, because the ultimate thinking is "no one in their right mind would need an array of such a large one."

0
source

Source: https://habr.com/ru/post/1725284/


All Articles