Java Reference
In-Depth Information
ImageCache
class that demonstrates the
SoftReference
-based caching of an
Image
object.
The
main()
method first creates an
Image
instance by calling the
getImage()
class method; the instance's private
image
array occupies 100MB of memory.
main()
nextcreatesa
SoftReference
objectthatisinitializedtoan
Image
ob-
ject'sreference,andclearsthestrongreferencetothe
Image
objectbyassigning
null
to
image
.Ifthisstrongreferenceisnotremoved,the
Image
objectwillbecachedal-
ways and the application will most likely run out of memory.
After creating a byte array that's used to demonstrate
SoftReference
,
main()
enterstheapplication'smainloop,whichkeepsloopingaslongas
cache.get()
re-
turnsanonnullreference(the
Image
objectisstillinthecache).Foreachloopiteration,
main()
outputs a message stating that the
Image
object is still cached, and doubles
the size of the byte array.
At some point, the array doubling will exhaust the heap space. However, before it
throwsaninstanceofthe
java.lang.OutOfMemoryError
class,theJavaVirtual
Machine(JVM)willattempttoobtainsufficientmemorybyclearingthe
SoftRefer-
ence
object's
Image
reference, and removing the
Image
object from the heap.
The next loop iteration will detect this situation by discovering that
get()
returns
null.Theloopendsand
main()
outputsasuitablemessageconfirmingthatthe
Image
object is no longer cached.
main()
now assigns
null
to
b
to ensure that there will be sufficient memory to
reloadthelargeimage(via
getImage()
)andonceagainstoreitina
SoftRefer-
ence
-based cache.
Finally,
main()
entersafinitelooptodemonstratethatthereloaded
Image
object
is still in the cache.
ImageCache
). You should discover output that's similar to that shown here:
caching image
image is still cached
image is still cached
image is still cached
image is still cached
image is still cached
image is no longer cached