我正在使用 Java 中的二维 int
数组,它们是方形的,一行和一列可以有大约 30000 个元素,这意味着数组中有 30000^2*4 个字节,这小于 5GB(而且我有超过 5GB 的可用内存)。
我的程序的基本结构是这样的:
public class A {
public static void main(String[] args) {
Graph g = ...; // read from file
System.out.println(B.computeSomethingBig(g));
}
}
public class B {
public static computeSomethingBig(Graph g) {
int numVertices = g.numVertices();
System.out.println(numVertices); // ~30000 maximum
int[][] array = new int[numVertices][numVertices];
// ... other computations
}
}
现在,在 Eclipse 中,我使用这些参数在类 A
中运行 main
:
-Xms5g -Xmx10g
我有 numVertices
打印出一个大约 30000 的值,设置最小堆大小 (-Xms
) 似乎是不必要的。但是,我得到:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
最佳答案
运行以下内容:
public class A {
public static void main(String[] args) {
int numVertices = 30000;
int[][] array = new int[numVertices][numVertices];
}
}
没有任何参数,即java A
会导致OOM错误。运行 java -Xms5g -Xmx10g A
有效。我怀疑 numVertices 比您预期的要大。为什么不在分配之前输出它以确保。
还要考虑到您的 Graph
或应用程序中的其他对象也可能正在使用堆空间。
关于Java OutOfMemoryError 即使结构正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25439022/