4.14. Garbage collection
Last updated: 23 January 2013.
Garbage collection is the automatic process of reclaiming the memory allocated to objects that are no longer referenced by an application. Because the JVM provides automatic garbage collection, Java developers do not have to bother about manually freeing allocated memory.
How does garbage collection work?
When you create an object with the keyword new, memory is allocated to that object at runtime on the heap. When the object is no longer referenced in your application, it becomes eligible for garbage collection. When garbage collection starts, the method finalize provided by the super class Object is called on the object to be garbage collected and the allocated memory is freed by the garbage collector. Thus, that memory becomes available again for new objects.
If you need to release resources or perform some cleanup before an object is removed from memory, you have to override the method finalize provided by the super class Object.
Garbage collection can happen at any time. In particular, it is triggered when there is not enough memory left on the heap for a new object. You can explicitly send a garbage collection request to the JVM by calling the method gc provided by the class System but the request may not be honoured immediately because garbage collection cannot be forced.
Can garbage collection prevent an application from running out of memory?
Garbage collection cannot prevent an application from running out of memory if objects are created much faster than they are removed from the heap. An application may also create and hold references to objects that are no longer used. Consequently, those objects never become eligible for garbage collection and the application eventually runs out of memory. That issue is termed a memory leak.