我在 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 !!!!
}
}
最佳答案
这些对象将分配到为短期对象保留的空间中,只有在它们存活一段时间后才会移动到主堆。
如果您想准确了解您的应用程序创建的所有对象发生了什么,您确实需要使用分析器。
这里有更多信息:Java Memory explained (SUN JVM)
关于java - 如何使用 Runtime.freeMemory() 和 GC 跟踪 JVM 上的任何对象实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9809920/