implementavisitorpatterninordertomakepointerstootherheapobjectsknowntothe
garbagecollector.
Thesimplestwayofgettingextrainformationattachedtoallobjectsistoallocateaheaderin
frontofallobjectsintheheap.Objectsareallocatedinourheapusingtwobaseclasses:
GarbageCollectedandGarbageCollectedFinalized.GarbageCollectedobjectsareallocatedin
theOilpanheapbutwillnothavetheirdestructorscalledinordertospeedupfinalization.
Therefore,GarbageCollectedcanonlybeusedforobjectswithtrivial(empty)destructors.
GarbageCollectedFinalizedobjectsareallocatedintheOilpanheapandtheirdestructorsare
calledwhenthegarbagecollectordeterminesthattheobjectisdead.Inheritingfromoneof
thesebaseclassesmakessurethattheobjectisallocatedintheOilpanheapwithaheader:
TheheadercontainsafieldforthesizeandmarkbitandapointertoaGCinfoobject.Thereis
onestaticGCinfoobjectperrootofaninheritancehierarchythatisintheheap.GCinfoobjects
containacoupleoffunctionpointers.One,called‘trace’,fortheimplementationofthevisitor
patternandone,called‘finalize’,forafinalizertobecalledwhenthegarbagecollector
determinesthatanobjectisnolongerreachable(usuallycallingthedestructoroftheobject
directly).Allocatingaheaderlikethisinfrontofallobjectsleadstoasignificantoverhead.
Therefore,inreality,wespecializeheappagesforvariousobjecttypes.Ifagivenheappage
onlycontainsobjectsofonetype,theywillallhavethesameGCinfoobjectandwecanstore
theGCinfoobjectonthepageinsteadofinfrontofeachobject.Onthebranchwearecurrently
allocatingallNodeinstancesonseparatepages.Additionally,wecanspecializeonsizeaswell
andputthesize(andabitmapformarking)onthepagesinordertosavethesizefieldinthe
header.Wearenotcurrentlyspecializingonsize,butweplantodoso.
Givenheadersofthisform,markingisasimpleiterativealgorithm.Foreachobjectpointerinthe
rootset,markitbycheckingifitisalreadymarked.Ifitis,don’tdoanything.Ifitisn’t,markthe
objectandpushitonamarkingstacktogetherwiththe‘trace’methodfromitsGCinfoobject.
Then,whilethemarkingstackisnotempty,popanitemandcallits‘trace’method.Thetrace
methodisresponsibleformarkingallheappointerscontainedinthegivenobject.Thisleadsto
moreobjectsbeingpushedonthemarkingstack.Whenthemarkingstackisempty,allpointers
havebeentracedandallliveobjectshavebeenmarked.
Thesweepphasereclaimsunusedmemory.Itdoessobysweepingoverallobjectsintheheap.
Foreachobjectencountereditchecksiftheobjectismarked.Iftheobjectismarkeditis
reachableandshouldstayalive.Theobjectisunmarkedandsweepingmovesontothenext
object.Forunmarkedobjects,the‘finalize’methodfromtheGCinfoobjecthastobecalled,ifit
exists,andthememoryisreclaimedbyaddingittofreelists(adjacentfreeblocksare
coalesced).Ifcompletelyemptypagesareencounteredduringsweepingtheyaremarkedas
beingunusedsothesystemcanunmapthem.Forsecurity,wedonotactuallyunmapthe
4
评论3
最新资源