1

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

    }
}
Community
  • 1
  • 1
chrisapotek
  • 6,007
  • 14
  • 51
  • 85
  • Try `new String("foo" + i)` instead of `"foo" + i`. The literal string will be stored in the String pool. – Eng.Fouad Mar 21 '12 at 17:42
  • @Eng.Fouad Nope, that makes NO difference. It has to do with what David Tinker said. – chrisapotek Mar 21 '12 at 17:48
  • @Eng.Fouad You are maybe confusing with the `intern()` method, but the String(String) constructor just ensures that the referenced char[] is exactly of the size of the string – Guillaume Polet Mar 21 '12 at 17:50
  • You'll be able to do a much better job of monitoring memory usage via JMX. See [this question and its answers.](http://stackoverflow.com/questions/462677/programatically-get-heap-info-using-jmx-with-java-5) – erickson Mar 21 '12 at 17:52
  • Follow up question since freeMemory cannot be used => http://stackoverflow.com/questions/9810212/how-to-track-any-object-creation-in-java-since-freememory-only-reports-long-li – chrisapotek Mar 21 '12 at 17:59

1 Answers1

3

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)

Community
  • 1
  • 1
David Tinker
  • 9,383
  • 9
  • 66
  • 98
  • Got you, but I want to track ANY object creation on my program. Should I change my GC to something else that will write everything to the heap so I can track it with freeMemory() ? This is just for benchmarking, not for production. – chrisapotek Mar 21 '12 at 17:44
  • I don't think changing the GC will help. The memory stats are going to depend on when GC last happened etc. – David Tinker Mar 21 '12 at 17:47
  • I am opening a new question just for that, since freeMemory CANNOT be used => http://stackoverflow.com/questions/9810212/how-to-track-any-object-creation-in-java-since-freememory-only-reports-long-li – chrisapotek Mar 21 '12 at 17:59