Java Reference
In-Depth Information
reloading and recaching image
image is still cached
image is still cached
image is still cached
image is still cached
image is still cached
image is still cached
The WeakReference classdescribesa Reference objectwhosereferentisweakly
reachable.Aswellasinheriting Reference 'smethods,thisgenericclassprovidesthe
following constructors for initializing a WeakReference object:
WeakReference(T r) encapsulates r 'sreference.The WeakReference
objectbehavesasaweakreferenceto r .No ReferenceQueue objectisas-
sociated with this WeakReference object.
WeakReference(T r, ReferenceQueue<? super T> q) encap-
sulates r 's reference. The WeakReference object behaves as a weak refer-
ence to r . The ReferenceQueue object identified by q is associated with
this WeakReference object. Passing null to q indicates a weak reference
without a queue.
WeakReference is useful for preventing memory leaks related to hashmaps. A
memory leak occurs when you keep adding objects to a hashmap and never remove
them. The objects remain in memory because the hashmap stores strong references to
from elsewhere in the application. When an object's last strong reference (apart from
hashmap strong references) disappears, the object should be garbage collected.
This situation can be remedied by storing weak references to hashmap entries so
they are discarded when no strong references to their keys exist. Java's
java.util.WeakHashMap class (discussed in Chapter 5 ) , whose private Entry
static member class extends WeakReference , accomplishes this task.
Note Referencequeuesaremoreusefulwith WeakReference thantheyarewith
SoftReference .Inthecontextof WeakHashMap ,thesequeuesprovidenotifica-
tionofweaklyreferencedkeysthathavebeenremoved.Codewithin WeakHashMap
Search WWH ::

Custom Search