How to track any object instantiation on my JVM wi

2019-07-29 09:12发布

问题:

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)