How to track any object instantiation on my JVM with Runtime.freeMemory() and GC

我怕爱的太早我们不能终老 提交于 2020-01-05 07:08:24

问题


I am using the default GC with 1.6.0_27-b07 (Sun's JRE) and because of this I am not able to detect an increase in memory with Runtime.getRuntime().freeMemory(). Can anyone shed a light on how to accomplish this? Do I have to use a different GC? Which one?

The simple program below prints 0 for the memory allocated. :( :( :(

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 !!!!

    }
}

回答1:


Those objects will be allocated in space reserved for short lived objects and only moved to the main heap if they survive for a while.

You really need to use a profiler if you want to see exactly whats happening with all the objects your application creates.

Here is some more info: Java Memory explained (SUN JVM)



来源:https://stackoverflow.com/questions/9809920/how-to-track-any-object-instantiation-on-my-jvm-with-runtime-freememory-and-gc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!