【问题标题】:How to track any object instantiation on my JVM with Runtime.freeMemory() and GC如何使用 Runtime.freeMemory() 和 GC 在我的 JVM 上跟踪任何对象实例化
【发布时间】: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


【解决方案1】:

这些对象将在为短期对象保留的空间中分配,并且只有在它们存活一段时间后才会移动到主堆。

如果您想准确了解您的应用程序创建的所有对象发生了什么,您确实需要使用分析器。

这里有更多信息:Java Memory explained (SUN JVM)

【讨论】:

  • 知道了,但我想跟踪我的程序上的任何对象创建。我是否应该将我的 GC 更改为将所有内容写入堆的其他东西,以便我可以使用 freeMemory() 跟踪它?这仅用于基准测试,而不是用于生产。
  • 我认为更改 GC 不会有帮助。内存统计将取决于上次发生 GC 的时间等。
  • 我正在为此打开一个新问题,因为无法使用 freeMemory => stackoverflow.com/questions/9810212/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多