Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection

 
annapurna madala
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

public class GarbageCollector{
public static void main(String args[]){
Runtime runtime = Runtime.getInstance();
String s ;
System.out.println(runtime.totalMemory());
System.out.println(runtime.freeMemory());
for(int i=0;i<1000;i++)
s = new String("");
System.out.println(runtime.freeMemory());
runtime.gc();

System.out.println(runtime.freeMemory());
}
}

the above code prints:
2025678
1789000
1749899
1898122

Now when i run this program again, the first print statement for the free memory should give me 1898122 bytes , instead i get 1789000 as the output

i would like to know the reason behind this

thanks
annapurna
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cant guarantee that java will allocate x total memory and have y free memory at any point of time. How do you even know that all those Strings got Gced ?
 
annapurna madala
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The last print statement says it all, the unused memory is garbage collected
but my point is not whether the Strings are garbage collected or not but why is the free memory displayed as 1789000, when in the previous run i get the free memory as 1898122
 
Nidhi Singhal
Ranch Hand
Posts: 89
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calling runtime.gc() does not gaurantee that the garbage collector is running. So you cannot depend on it to free memory at that instant of time. All the strings might not have been gced at the time when runtime.gc() is called. This might explain the difference in amount of free memory.

- Nidhi
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic