Skip to content
Advertisement

OutOfMemoryError on 10000×10000 int array in eclipse

I was wrote a little scratch program to check the time of looping through a 2 dimensional array by rows or columns, since I remembered that one way was much faster for large data sets, but I couldn’t remember which way. I ran into an interesting error when I ran my program though.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at testing.ForLoopTest.main(ForLoopTest.java:10)

Now in my test I am using a int[10000][10000] running from in eclipse with the default heap settings. I know that I can increase the heap size, but my gut tells me that this should run just fine without me needing to do that. Is this normal? Is there something silly in my code that I am not seeing?

Here is my code

public static void main(String[] args){
    final int arrSize = 10000;
    long start = 0;
    long rowFirstTime = 0;
    long colFirstTime = 0;
    int[][] arr = new int[arrSize][arrSize];

    start = System.currentTimeMillis();
    for(int x = 0; x < arrSize; x++){
        for(int y = 0; y < arrSize; y++){
            arr[x][y] = -1;
        }
    }
    rowFirstTime = System.currentTimeMillis() - start;
    start = System.currentTimeMillis();
    for(int y = 0; y < arrSize; y++){
        for(int x = 0; x < arrSize; x++){
            arr[x][y] = 0;
        }
    }
    colFirstTime = System.currentTimeMillis() - start;
    System.out.println("row time is " + rowFirstTime);
    System.out.println("col time is " + colFirstTime);
}

The error happens on array initialization, it doesn’t get to the for loops.

Thanks, zdevex

Advertisement

Answer

You are trying to allocate memory for 10 000 arrays of length 10 000. This requires lots of memory (about 400 MiB, by a raw calculation), which are unavailable in your JVM. This causes your OutOfMemoryError.

Try to augment the amount of memory allocated to your JVM in the execution arguments. You are looking at something like the -Xmx argument. Try giving it a value greater than 400 MiB. I think you might be able to change this value in the project properties in Eclipse.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement