File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage Collection" Watch "Garbage Collection" New topic

Garbage Collection

annapurna madala

Joined: Oct 30, 2006
Posts: 6
hi all,

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


the above code prints:

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

Deepak Bala

Joined: Feb 24, 2006
Posts: 6662

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

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:
subject: Garbage Collection
It's not a secret anymore!