Destroying and Finalizing Objects
Now that we’ve seen how new objects are created and initialized in Java, we need to study the other end of the object life cycle and examine how objects are finalized and destroyed. Finalization is the opposite of initialization.
In Java,
the memory occupied by an object is automatically reclaimed when the
object is no longer needed. This is done through a process known as
garbage collection. Garbage collection is a
technique that has been around for years in languages such as Lisp.
It takes some getting used to for programmers accustomed to such
languages as C
and C++, in which you must call the free()
function or the delete
operator to reclaim memory.
The fact that you don’t need to remember to destroy
every object you create is one of the features that makes Java a
pleasant language to work with. It is also one of the features that
makes programs written in Java less prone to bugs than those written
in languages that don’t support automatic garbage
collection.
Garbage Collection
The Java interpreter knows exactly what objects and arrays it has allocated. It can also figure out which local variables refer to which objects and arrays and which objects and arrays refer to which other objects and arrays. Thus, the interpreter is able to determine when an allocated object is no longer referred to by any other active object or variable. When the interpreter finds such an object, it knows it can safely reclaim the object’s memory and does so. The garbage ...
Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.