【发布时间】:2012-04-06 06:50:00
【问题描述】:
我正在使用带有 1.6.0_27-b07(Sun 的 JRE)的默认 GC,并且由于 this,我无法通过 Runtime.getRuntime().freeMemory() 检测到内存增加。谁能阐明如何做到这一点?我必须使用不同的 GC 吗?哪一个?
下面的简单程序为分配的内存打印 0。 :( :( :(
import java.util.HashSet;
import java.util.Set;
public class MemoryUtils {
private static Set<String> set = new HashSet<String>();
public static void main(String[] args) {
long mem = Runtime.getRuntime().freeMemory();
// now create a bunch of objects and save them in the set
for (int i = 0; i < 100; i++) {
set.add("foo" + i);
}
long allocated = mem - Runtime.getRuntime().freeMemory();
System.out.println("Memory allocated: " + allocated); // ===> GIVES 0 !!!!
}
}
【问题讨论】:
-
尝试
new String("foo" + i)而不是"foo" + i。文字字符串将存储在字符串池中。 -
@Eng.Fouad 不,这没什么区别。这与大卫·廷克所说的有关。
-
@Eng.Fouad 您可能对
intern()方法感到困惑,但 String(String) 构造函数只是确保引用的 char[] 与字符串的大小完全相同 -
您将能够通过 JMX 更好地监控内存使用情况。见this question and its answers.
-
由于 freeMemory 无法使用,请跟进问题 => stackoverflow.com/questions/9810212/…
标签: java optimization memory garbage-collection benchmarking