在使用runtime.gc()
创建测试数组之前,请尝试进行垃圾回收。
如果您不是每次都创建全新的JVM,则可能会受到具有不同启动状态的影响。
我的程序可以处理大于1的数值,例如1.25。但是当数值过大时,会出现“堆空间”异常。
这里,也许你想用 'maxMemory()' 代替。
public class Mem2 {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
runtime.gc();
long freeMemory = runtime.freeMemory();
double factor = 1.29;
int size = (int) (factor * freeMemory);
System.out.println(" freememory is " + freeMemory);
System.out.println(" size is " + size);
System.out.println("the total memory is " + runtime.totalMemory());
System.out.println(" the max memory is " + runtime.maxMemory());
byte[] testArray = new byte[size];
}
}
输出:
freememory is 84466864
size is 108962254
the total memory is 85000192
the max memory is 129957888
Process finished with exit code 0
看起来有大约20M我无法解释。
我认为totalMemory()是JVM当前分配的内存量,freeMemory()是已使用的内存量,maxMemory()是硬限制。
通过您代码的这个变体,您可以看到totalMemory()
和freememory()
之间的相互作用。
public class Mem3 {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
for (int i = 0; true; i++) {
runtime.gc();
int size = i * 10000000;
System.out.println(" i is " + i);
System.out.println(" size is " + size);
System.out.println("b freememory is " + runtime.freeMemory());
System.out.println("b the total memory is " + runtime.totalMemory());
System.out.println("b the max memory is " + runtime.maxMemory());
byte[] testArray = new byte[size];
System.out.println(" array " + testArray.length);
System.out.println("a freememory is " + runtime.freeMemory());
System.out.println("a the total memory is " + runtime.totalMemory());
System.out.println("a the max memory is " + runtime.maxMemory());
System.out.println(" ");
}
}
}
如果你运行它并查看之前和之后的值,你就可以看到发生了什么。请注意在第6次和第7次迭代之间发生了什么:
i is 6
size is 60000000
b freememory is 84300496
b the total memory is 85000192
b the max memory is 129957888
array 60000000
a freememory is 24300472
a the total memory is 85000192
a the max memory is 129957888
i is 7
size is 70000000
b freememory is 84300496
b the total memory is 85000192
b the max memory is 129957888
array 70000000
a freememory is 59258168
a the total memory is 129957888
a the max memory is 129957888
我们可以从第6行看到,在分配了60M之后,还剩下约24M。然而,在第7行中,我们已经超过了一个阈值。更多的内存已被分配(请注意totalMemory),而freeMemory现在只有不到60M。
factor
值较大时失败的原因之一是您要求连续的字节数组。通过使用较小的块,您可以分配更多的总内存。 - clstrfsck