Java Reference
In-Depth Information
weakly reachable, all WeakReference objects that refer to that ob-
ject will be cleared. The object then becomes finalizable and after
finalization will be reclaimed (assuming it is not resurrected) un-
less it is phantom reachable.
A phantom reachable object isn't really reachable in the normal
sense because the referent object cannot be accessed via a
PhantomReferenceget always returns null . But the existence of the
phantom reference prevents the object from being reclaimed until
the phantom reference is explicitly cleared. Phantom references
allow you to deal with objects whose finalize methods have been
invoked and so can safely be considered "dead." Phantom refer-
ences are used in conjunction with the reference queues we dis-
cuss in the next section.
Both SoftReference and WeakReference declare a constructor that takes a
single referent object. All three classes declare a two-argument con-
structor that takes a referent object and a ReferenceQueue .
Soft references provide you with a kind of caching behavior, clearing
older references while trying not to clear new or used ones. Consider
our web browser scenario. If you maintain your images in soft refer-
ences, they will be reclaimed as memory runs low. Images are prob-
ably relatively unimportant to keep in memory should memory run low,
and clearing the oldest or least used images would be a reasonable ap-
proach. In contrast, if you used weak references then all images would
be reclaimed as soon as memory got lowthis would probably induce a lot
of overhead as you reload images that it may not have been necessary
to get rid of in the first place.
Weak references are a way of holding a reference to an object but say-
ing "reclaim this object if this is the only type of reference to it."
Consider the following method that returns data read into memory from
a file. The method has been optimized under the assumption that the
same file is often named more than once in a row and that reading the
data is expensive:
 
Search WWH ::




Custom Search