简体   繁体   中英

Confused on result of the implementation for testing object memory consumption in java

I use the below implemenatation to test the memory consumption of the java objects.
But it prints usage as 104936 B when the i limit is from 384 to 1694 in the calling method's for loop.
It prints usage as 0B for when the above i limit is less than 384.

Why is this?

  • IDE : eclipse kepler
  • java : 1.5 (this acts differently when the java version is also changed)
  • OS : Ubuntu 12.10

     public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); long totalStart = runtime.totalMemory(); long start = runtime.freeMemory(); SampleTester sampleTester = new SampleTester(); sampleTester.callingMethod(); long totalEnd = runtime.totalMemory(); long end = runtime.freeMemory(); System.out.println("Usage [(("+totalEnd+"-"+end+") - ("+totalStart+"-"+start+"))] \\t: " + ((totalEnd-end) - (totalStart-start))); } private void callingMethod(){ for(int i = 0; i < 1694; i++){ ArrayList<String> arrayList = new ArrayList<String>(); } } 

Each ArrayList you create is immediately eligible for GC when the current loop iteration ends.

So theoretically the JVM could allocate each ArrayList in the space formerly occupied by the one from the last iteration and only need one "slot", which gets discarded when the last iteration ends and the method exists.

That explains the "0" value (this or a similar optimization).

In practice, the JVM doesn't always do that, but will leave eligible object uncollected for some time in order to be more performant (because doing GC too often can be just as bad for performance).

When and how the JVM decides which optimization to apply is entirely implementation-defined and knowing the very details is rarely useful information (because you can't depend on it and it can change with the next version).

So if you want to find out how much memory n ArrayList object need, make sure that you each one of those is actually reachable and as such not eligible for garbage collection when you check the current used memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM