Java Reference
In-Depth Information
17.1. Garbage Collection
Objects are created with new , but there is no corresponding delete oper-
ation to reclaim the memory used by an object. When you are finished
with an object, you simply stop referring to itchange your reference to
refer to another object or to null , or return from a method so its local
variables no longer exist and hence refer to nothing. Objects that are no
longer referenced are termed garbage, and the process of finding and re-
claiming these objects is known as garbage collection.
The Java virtual machine uses garbage collection both to ensure any ref-
erenced object will remain in memory, and to free up memory by dealloc-
ating objects that are no longer reachable from references in executing
code. This is a strong guaranteean object will not be collected if it can be
reached by following a chain of references starting with a root reference,
that is, a reference directly accessible from executing code.
In simple terms, when an object is no longer reachable from any execut-
able code, the space it occupies can be reclaimed. We use the phrase
"can be" because space is reclaimed at the garbage collector's discretion,
usually only if more space is needed or if the collector wants to avoid run-
ning out of memory. A program may exit without running out of space or
even coming close and so may never need to perform garbage collection.
An object is "no longer reachable" when no reference to the object exists
in any variable of any currently executing method, nor can a reference
to the object be found by starting from such variables and then following
each field or array element, and so on.
Garbage collection means never having to worry about dangling referen-
ces. In systems in which you directly control when objects are deleted,
you can delete an object to which some other object still has a refer-
ence. That other reference is now dangling, meaning it refers to space
that the system considers free. Space that is thought to be free might
be allocated to a new object, and the dangling reference would then ref-
erence something completely different from what the object thought it
referenced. This situation could cause all manner of havoc when the pro-
gram uses the values in that space as if they were part of something
they are not. Garbage collection solves the dangling reference problem
 
Search WWH ::




Custom Search