简体   繁体   中英

How to simulate the Out Of memory : Requested array size exceeds VM limit

I used the Out Of Memory help from sun's site . Where it is quoted as

Out Of Memory : Requested array size exceeds VM limit

This indicates that the application attempted to allocate an array that is larger than the heap size. For example, if an application tries to allocate an array of 512MB but the maximum heap size is 256MB, then this error will be thrown. In most cases the problem is likely to be either that the heap size is too small or that a bug results in the application attempting to create an array whose size is calculated to be incorrectly huge.

I tried to simulate this by

import java.util.ArrayList;
import java.util.List;

public class JavaTest {
    public static void main(String[] args){
        long[] ll = new long[64*1024*1024];
    }
}

on my machine with

javac *.java;java -Xmx256m JavaTest

But the above line is producing

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at JavaTest.main(JavaTest.java:7)

What am I missing?

Update : My java version is

$java -version
java version "1.6.0_15"
Java(TM) SE Runtime Environment (build 1.6.0_15-b03)
Java HotSpot(TM) Server VM (build 14.1-b02, mixed mode)

For me

long[] l = new long[Integer.MAX_VALUE];

yields Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit

PS: if you need to produce the exception for the purpose of testing, you could also just throw new OutOfMemoryError("Requested array size exceeds VM limit") yourself.

The array is allocated as continous heap space and memory can get fragmented due to object allocaion and garbage collection. The out of memory error occurs due to lack of a solid block of memory to allocate the array. Did you sent the JVM memory explicitly with -Xmx flag ?

尝试分配一个ArrayList并将其大小运行时间加倍。

Just looking at example fo people have the problem it seems to occur when people are using the java native interface, bridge between C++ applications.

When running pure java application the standard procedure seems for allocating an array is calculate the bytes needed from the size variable passed in the array deceleration throwing an java.lang.OutOfMemoryError: Java heap space exception.

When the array is created outside the JVM it looks it generates this other exception. I'm sure there is some technical reason for this different behavior.

You could try replicating the problem this person describes on this other forum .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM