0

I am executing following code in eclipse:

public static void main(String args[]) { 
  long before=Runtime.getRuntime().freeMemory();
  Object o=new Object();

  Long after=Runtime.getRuntime().freeMemory();
  System.out.println(before-after);
}

But output I'm getting is 0. I am trying to figure out why freeMemory method is not reducing heap space after object creation?

thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23
Mu.Arg
  • 11
  • 4
  • Possible duplicate of [Runtime - why is freeMemory() not showing memory consumed correctly?](http://stackoverflow.com/questions/3421869/runtime-why-is-freememory-not-showing-memory-consumed-correctly) – Roman Oct 03 '15 at 20:24

3 Answers3

0

try to put Runtime.getRuntime().gc(); at the beginning and you'll see a change

for further explanations, see Runtime - why is freeMemory() not showing memory consumed correctly?

Community
  • 1
  • 1
0

To measure object sizes you should use jol.

the8472
  • 40,999
  • 5
  • 70
  • 122
0

Java/JVM is a Garbage Collection language. Memory allocation and release is completely managed by Garbage Collector and such a memory release occurs when JVM goes through a Young Generation Garbage collection or Full Garbage collection. It is again based on GC type you have like Serial GC, Parallel GC, etc.

Additionally: When JVM found freeMemory() method, it only returns a value of how much JVM free memory is available for new objects to be allocated but not a call to free up or release memory.

So, freeMemory() method has no effect in looking out your objects and free them. Also, in a Garbage collected language, you have no way to release memory for any specific objects directly but it happens only through a grabage collection call. Also, some types of JVM (like CMS collector) marks an object to be freed during its next Garbage Collection cycle (the young GC) provided your object is not a tenured object promoted to old generation before the collection occurred. The actual memory release in such GC happens during its Sweep phase. Read more on Garbage collector types like Serial GC, Parallel GC, CMS, G1GC and only then you would understand under what specific conditions and JVM initialization settings -you could expect a Garbage collection call and garbage collection type (young collection or a Full GC collection) being triggered which releases memory allocated.

Chaitanya P
  • 120
  • 7