Java Reference
In-Depth Information
17.5. Reachability States and Reference Objects
An object can be garbage collected only when there are no references to
it, but sometimes you would like an object to be garbage collected even
though you may have a specific reference to it. For example, suppose
you are writing a web browser. There will be images that have been seen
by the user but that are not currently visible. If memory becomes tight,
you can theoretically free up some memory by writing those images to
disk, or even by forgetting about them since you can presumably refetch
them later if needed. But since the objects representing the images are
referenced from running code (and hence reachable ) they will not be re-
leased. You would like to be able to have a reference to an object that
doesn't force the object to remain reachable if that is the only reference
to the object. Such special references are provided by reference objects.
A reference object is an object whose sole purpose is to maintain a refer-
ence to another object, called the referent. Instead of maintaining direct
references to objects, via fields or local variables, you maintain a direct
reference to a reference object that wraps the actual object you are in-
terested in. The garbage collector can determine that the only references
to an object are through reference objects and so can decide whether to
reclaim that objectif the object is reclaimed then, the reference object is
usually cleared so that it no longer refers to that object. The strength of
a reference object determines how the garbage collector will behavenor-
mal references are the strongest references.
17.5.1. The Reference Class
The classes for the reference object types are contained in the package
java.lang.ref . The primary class is the generic, abstract class Referen-
ce<T> , which is the superclass of all the specific reference classes. It has
four methods:
public T get()
Returns this reference object's referent object.
 
Search WWH ::




Custom Search