Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java requires larger heap space than what is reasonable

Tags:

java

I have a program where I will be using a very large short[] array:

import java.lang.Math;

public class HPTest {

    public static void main(String[] args) {
        int n = 30;
        short[] a = new short[(int)Math.pow(2,n)];
    }
}

As far as I know, a short[] array should use 2 bytes per element, and so an array with 2^30 elements should need about 2 GiB of RAM.

In order to run the program, I therefore tried

java -Xms2000m HPTest

but still got a heap space error. Even at 3000m I got the same error, but at 4000m it worked.

Any ideas as to why I had to go so far above the estimated limit of 2000m?

EDIT: As has been pointed out by many users, I made a very embarrassing error in declaring that a short needs 1 byte rather than 2 bytes. The question then should be why it doesn't suffice with 2000m.

like image 605
Alexandre Vandermonde Avatar asked Feb 25 '16 18:02

Alexandre Vandermonde


People also ask

What is the recommended heap size in Java?

It is recommended to increase the Java heap space only up to one-half of the total RAM available on the server. Increasing the Java heap space beyond that value can cause performance problems. For example, if your server has 16 GB of RAM available, then the maximum heap space you should use is 8 GB.

How big should be heap size?

The heap size value is determined by the amount of memory available in the computer. Initial heap size is 1/64th of the computer's physical memory or reasonable minimum based on platform (whichever is larger) by default.

What is the max heap size for 64 bit JVM?

For 64 bit platforms and Java stacks in general, the recommended Maximum Heap range for WebSphere Application Server, would be between (4096M - 8192M) or (4G - 8G).

What is maximum heap size for JVM?

The default maximum Java heap size is 256 MB.


1 Answers

Something this large, will be much happier outside the heap. You would be better off looking in to NIO and using direct byte buffers to back your large Short array. This memory can be kept out of the heap, and away from the mitts of the garbage collector (who may at times feel inclined to want to copy your buffer from one area to the other).

See java.nio.ShortBuffer and start digging from there.

like image 100
Will Hartung Avatar answered Sep 26 '22 14:09

Will Hartung