• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Garbage Collection

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 89
Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic