Java Reference
In-Depth Information
stack is empty
null
Thereisaproblemwiththe
Stack
class:itleaksmemory.Whenyoupushanobject
ontothestack,itsreferenceisstoredintheinternal
elements
array.Whenyoupopan
objectoffthestack,theobject'sreferenceisobtainedand
top
isdecremented,butthe
reference remains in the array (until you invoke
push()
).
Imagine a scenario where the
Stack
object's reference is assigned to a class field,
whichmeansthatthe
Stack
objecthangsaroundforthelifeoftheapplication.Further-
more,supposethatyouhavepushedthree50-megabyte
Image
objectsontothestack,
andthensubsequentlypoppedthemoffthestack.Afterusingtheseobjects,youassign
null
totheirreferencevariables,thinkingthattheywillbegarbagecollectedthenext
timethegarbagecollectorruns.However,thiswon'thappenbecausethe
Stack
object
stillmaintainsitsreferencestotheseobjects,andso150megabytesofheapspacewill
not be available to the application, and maybe the application will run out of memory.
The solution to this problem is for
pop()
to explicitly assign
null
to the
ele-
ments
entry prior to returning the reference. Simply uncomment the
ele-
ments[top+1] = null;
line in
Listing 2-49
to make this happen.
You might think that you should always assign
null
to reference variables when
their referenced objects are no longer required. However, doing so often does not
improve performance or free up significant amounts of heap space, and can lead to
throwninstancesofthe
java.lang.NullPointerException
classwhenyou're
erage of Java's exceptions-oriented language features). You typically nullify reference
variablesinclassesthatmanagetheirownmemory,suchastheaforementioned
Stack
class.
Note
Garbage collection is a complex process and has resulted in various garbage
collectorsbeingdevelopedfortheJVM.Ifyouwanttolearnmoreaboutgarbagecol-
lection,Irecommendthatyoustartbyreadingthe“MemoryManagementintheJava
HotSpotVirtual Machine” whitepaper at
http://www.oracle.com/technet-
per-1-150020.pdf
.
Next,youwillwanttolearnabouttheGarbage-Firstcollector,
whichisnewinJava7.Checkout“TheGarbage-FirstGarbageCollector”whitepaper
g1-intro-jsp-135488.html
)
tolearnaboutthisgarbagecollector.Foraddition-
alinformationonJava'sgarbagecollectionprocess,youcanexploretheotherwhitepa-