aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage Collection" Watch "Garbage Collection" New topic
Author

Garbage Collection

annapurna madala
Greenhorn

Joined: Oct 30, 2006
Posts: 6
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

Joined: Feb 24, 2006
Posts: 6662
    
    5

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 ?


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
annapurna madala
Greenhorn

Joined: Oct 30, 2006
Posts: 6
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

Joined: Sep 19, 2004
Posts: 89

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Garbage Collection