Question

everyone. I am working on a project. Along the way, I got the "OutOfMemory" problem with this line of code...

this.A = new int[n][n];

...for n = 10000;

I tried fixing it by adding -Xmx2048m command but the thing is when added, all of the rest of running programs stops responding. Any other suggestion for my case? Thanks a lot

Was it helpful?

Solution

You have to calculate the space that array needs. If it is over 2048M then you'll receive an OutOfMemoryError.

In your case you try to allocate an array of 10000 x 10000 which is 100.000.000.

A primitive int occupies 4 bytes. This means that the whole array takes

100.000.000 * 4 bytes which is 0,37 GB of space.

So it seems that there is something else in your program which caueses the error. For example if you try to allocate multiple arrays in a loop then you can run out of memory real quick.

It can be a problem if your hardware does not have 2048M of memory.

It is also possible that before using -Xmx2048m you had for example -Xmx512m which might be too small for your array.

OTHER TIPS

Use this:

Increase heap size in Java

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

java -Xms16m -Xmx64m ClassName

Let's see...

An int occupies 32bit or 4 bytes in memory.
Your 2-dimensional array thus requires 10000 * 10000 * 4 bytes = 400000000 bytes = 381.47 MB (plus storage for the array objects)

Let's verify that with a simple test:

int n = 10000;
int[][] foo = new int[n][n];
System.out.println("USED MEMORY: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024);

Result: 384 MB (on my machine, your results may vary).

Running out of memory in the heap happens when a requested block of memory cannot be allocated, not necessarily when the memory is full.

As you allocate memory in blocks of 40'000 bytes, you can run out of memory when no contiguous free memory of that size is available (hundreds of blocks with less that 40'000 won't help here). That means you can easily run out of memory when the free memory on the heap is fragmented as small memory blocks.

If you happen to allocate that memory multiple times in a row, try reusing the allocated memory instead of allocating it again (to prevent fragmentation to a certain degree). Alternatively, try using smaller arrays (even if it means using more of them).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top