• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to free memory?  RSS feed

 
Em Aiy
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Few days back i was asked a question during an interview that here is a code snippet



now the foo variable is referencing to a Foo object in the memory. How would we free this memory.

I replied that we can do it as


De referencing the reference variable will make the object clean ready for the Garbage Collector, but again, we are not sure whether the garbage collector will clean it or not (i read it somewhere on java GC that you cann't 100% sure that GC will clean every de-referenced objecT).

So my question is, how can we re-claim an allocated memory and we are 100% sure that the memory is re-claimed??

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shut down the JVM. Honestly, that is the only way to guarantee that the memory is cleaned up.

The garbage collector may never clean up an object, even if there are no more references to that object. You can't force it either. You can ask it politely using System.gc(), but the garbage collector can deny your request.

You can help the garbage collector by making sure you don't have any unused references, and perhaps by calling System.gc(), but that's all you can do and it doesn't guarantee anything.
 
Em Aiy
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:Shut down the JVM. Honestly, that is the only way to guarantee that the memory is cleaned up.

The garbage collector may never clean up an object, even if there are no more references to that object. You can't force it either. You can ask it politely using System.gc(), but the garbage collector can deny your request.

You can help the garbage collector by making sure you don't have any unused references, and perhaps by calling System.gc(), but that's all you can do and it doesn't guarantee anything.

lol @ shut down JVM .. :p .. i din answer that .. .. ;)

so, there is no explicit way that we can be sure to free the memory? why is it so ? and why GC does not guarantee of cleaning an un-referenced objecT?
 
Ryan Beckett
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't enforce it because its a daemon (low priority thread that runs in the background).
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!