简体   繁体   English

大型矩阵的java.lang.OutOfMemoryError

[英]java.lang.OutOfMemoryError with large Matrix

I have int K as an input (K will be between 0 and 1000000 (one million), inclusive) and I would like then to create a matrix of integers with height and width 2 times longer than K number, plus 1 element more. 我将int K作为输入(K将在0到1000000(包括一百万)之间,并且我想创建一个整数矩阵,其高度和宽度是K数的2倍,再加上1个元素。

Example if K=3, my matrix would be matrix[3*2+1][3*2+1]=matrix[7][7] if K=178754, my matrix would be matrix[357503][357503] 例如,如果K = 3,我的矩阵将是矩阵[3 * 2 + 1] [3 * 2 + 1] =矩阵[7] [7]如果K = 178754,我的矩阵将是矩阵[357503] [357503]

I got an java.lang.OutOfMemoryError: Java heap space exception in thread "main" 在线程“ main”中遇到了java.lang.OutOfMemoryError:Java堆空间异常

int height;
int width;
int [][] matrix;

    public int getKthNumber(int N, int K, String direction) {

    this.height = (K * 2) + 1;
    this.width = (K * 2) + 1;

    ****matrix = new int[this.width][this.height];****   // error here

Does anyone knows how to solve this little problem since I believe that the whole other code is OK ?? 有谁知道如何解决这个小问题,因为我相信整个其他代码都可以吗?

my matrix would be matrix[357503][357503] 我的矩阵应该是matrix [357503] [357503]

Yes .That's all enough to get out of memory. 是的,这足以使内存耗尽。 JVM tries to allocate memory for 357503X357503 of integers, where as each integer carries 32 bits which resulting ~476GB almost. JVM尝试为整数357503X357503分配内存,其中每个整数携带32位,这几乎导致476GB。

What actually you are trying to do ? 您实际上想做什么?

In a 32 bit system you can have up to 2GB . 在32位系统中,最多可以有2GB。 On a 64 bit system you can get more. 在64位系统上,您可以获得更多。

Command line flags are: 命令行标志是:

java -Xmx2g myprogram

But in your case it seems that this will not be enough, since 357503*357503*4/1024/1024/1024 (4 for bytes for integer) which is about 476G, so I think that you should rethink your solution. 但是在您的情况下,这似乎还不够,因为357503 * 357503 * 4/1024/1024/1024(4表示整数字节)大约为476G,因此我认为您应该重新考虑您的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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