When an instance of a class no longer has any references to it, it becomes a candidate for removal from memory.  This is identification of unreferenced objects and removal is called “garbage collection”.  Garbage collection occurs at times convenient for the JVM, which are usually inconvenient times for the developer.  If the JVM is busy, or there are not many objects waiting for removal, garbage collection may not occur at all.  Sun deliberately kept the method of memory management non-specific to allow for a broad range of garbage collection algorithms.

Normally a finalize() method is called on a class when it is garbage collected.  Some classes, such as InputStream use this method to close any files that are still open, but since garbage collection cannot be guaranteed to occur in a reasonable time it is a bad idea to depend on the cleanup.  The Java specification says that even calling System.gc() to try to force a garbage collection is not guaranteed to occur.

:
System.gc();
:

Since it may not execute anything, the above command may as well not be in the source.  

Exception: while garbage collection cannot be guaranteed to work at a specific time, it does work well.  Objects in memory that are no longer referenced will be cleaned up, guaranteed.  You do not have to manage these yourself.

blog comments powered by Disqus