Java: Maximum length of array

The maximum length of an array in Java is 2,147,483,647 (i.e. the maximum size of an int, 231 − 1).

This is the theoretical limit implied by the fact that the size of an array creation expression must be of type int. In practice there are two additional limits in effect:

Available Memory

The entire array is allocated up front, so the size of the array can not exceed the amount of free memory.

JVM Implementation

Some JVMs reserve a small part of the array for header information, and bail out with an OutOfMemoryError for array sizes that are close to the theoretical limit. In the HotSpot VM For example, the max_array_length function states the following:

// It should be ok to return max_jint here, but parts of the code
// (CollectedHeap, Klass::oop_oop_iterate(), and more) uses an int for
// passing around the size (in words) of an object. So, we need to avoid
// overflowing an int when we add the header. See CRs 4718400 and 7110613.
return align_down(max_jint - header_size(type), MinObjAlignment);

This reduces the effective limit to Integer.MAX_INT - 5.

You don't always know what JVM your code will be running on, so to be safe you can follow the approach taken in the core libraries and give a little bit more leeway for the JVM. From the ArraysSupport class:

/**
 * The maximum length of array to allocate (unless necessary).
 * Some VMs reserve some header words in an array.
 * Attempts to allocate larger arrays may result in
 * {@code OutOfMemoryError: Requested array size exceeds VM limit}
 */
public static final int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8;

Comments

Be the first to comment!