Video in progress

Strong Junior ⚙️ JVM and memory

How does "OutOfMemoryError: Requested array size exceeds VM limit" differ from "Java heap space"?

This error does not mean the heap is full. It means the requested array length exceeds the maximum the JVM allows (roughly Integer.MAX_VALUE). Making the heap bigger doesn't help, because the array simply can't be that large.

📖 Answer

In Java an array index is an int, so the theoretical limit is Integer.MAX_VALUE (~2.1 billion). HotSpot reserves a little room for the header, so the practical limit is a few elements below that. Go past it and you get this error, even if the heap has 100 GB free.

"Java heap space" is a different thing: the array length is valid, but no space could be found for it.

Where you run into it:

// Trying to read a 1.5 GB file into one array. This still works
byte[] all = Files.readAllBytes(path);

// A 3 GB file does not fit in an int, so you get an OOM or another error
ByteArrayOutputStream out = new ByteArrayOutputStream();
in.transferTo(out);  // the internal array doubles in size and hits the limit

When ArrayList, StringBuilder and ByteArrayOutputStream grow their internal arrays, they get close to this limit. The JDK uses a "soft" maximum for them (around Integer.MAX_VALUE - 8).

The fix is almost always a design change: instead of collecting big data into one array, stream it, process it in chunks, or work with a FileChannel or a memory-mapped file. If you see this error in the log, the first question is "why are we loading all of this data into memory at once?"