Java Reference
In-Depth Information
value is negative, or
InterruptedException
when this wait is interrup-
ted.
SoftReference
The
SoftReference
class describes a
Reference
object whose referent is softly
reachable. As well as inheriting
Reference
's methods and overriding
get()
, this
generic class provides the following constructors for initializing a
SoftReference
object:
•
SoftReference(T r)
encapsulates
r
'sreference.The
SoftReference
objectbehavesasasoftreferenceto
r
.No
ReferenceQueue
objectisasso-
ciated with this
SoftReference
object.
•
SoftReference(T r, ReferenceQueue<? super T> q)
encap-
sulates
r
'sreference.The
SoftReference
objectbehavesasasoftreferen-
ceto
r
.The
ReferenceQueue
objectidentifiedby
q
isassociatedwiththis
SoftReference
object.Passing
null
to
q
indicatesasoftreferencewithout
a queue.
SoftReference
is useful for implementing caches of objects that are expensive
timewise to create (e.g., a database connection) and/or occupy significant amounts of
heapspace,suchaslargeimages.Animagecachekeepsimagesinmemory(becauseit
takestimetoloadthemfromdisk)andensuresthatduplicate(andpossiblyverylarge)
images are not stored in memory.
Theimagecachecontainsreferencestoimageobjectsthatarealreadyinmemory.If
thesereferenceswerestrong,theimageswouldremaininmemory.Youwouldthenneed
tofigureoutwhichimagesarenolongerneededandremovethemfrommemorysothat
they can be garbage collected.
Having to manually remove images duplicates the work of a garbage collector.
However,ifyouwrapthereferencestotheimageobjectsin
SoftReference
objects,
thegarbagecollectorwilldeterminewhentoremovetheseobjects(typicallywhenheap
memory runs low) and perform the removal on your behalf.
Listing 4-8.
Caching an image
import java.lang.ref.SoftReference;
class Image