Tải bản đầy đủ - 0 (trang)
Chapter 17. Garbage Collection and Memory

Chapter 17. Garbage Collection and Memory

Tải bản đầy đủ - 0trang

17.1.GarbageCollection

Objectsarecreatedwithnew,butthereisnocorresponding

deleteoperationtoreclaimthememoryusedbyanobject.

Whenyouarefinishedwithanobject,yousimplystopreferring

toitchangeyourreferencetorefertoanotherobjectortonull,

orreturnfromamethodsoitslocalvariablesnolongerexist

andhencerefertonothing.Objectsthatarenolonger

referencedaretermedgarbage,andtheprocessoffindingand

reclaimingtheseobjectsisknownasgarbagecollection.

TheJavavirtualmachineusesgarbagecollectionbothtoensure

anyreferencedobjectwillremaininmemory,andtofreeup

memorybydeallocatingobjectsthatarenolongerreachable

fromreferencesinexecutingcode.Thisisastrongguaranteean

objectwillnotbecollectedifitcanbereachedbyfollowinga

chainofreferencesstartingwitharootreference,thatis,a

referencedirectlyaccessiblefromexecutingcode.

Insimpleterms,whenanobjectisnolongerreachablefrom

anyexecutablecode,thespaceitoccupiescanbereclaimed.

Weusethephrase"canbe"becausespaceisreclaimedatthe

garbagecollector'sdiscretion,usuallyonlyifmorespaceis

neededorifthecollectorwantstoavoidrunningoutof

memory.Aprogrammayexitwithoutrunningoutofspaceor

evencomingcloseandsomayneverneedtoperformgarbage

collection.Anobjectis"nolongerreachable"whennoreference

totheobjectexistsinanyvariableofanycurrentlyexecuting

method,norcanareferencetotheobjectbefoundbystarting

fromsuchvariablesandthenfollowingeachfieldorarray

element,andsoon.

Garbagecollectionmeansneverhavingtoworryaboutdangling

references.Insystemsinwhichyoudirectlycontrolwhen

objectsaredeleted,youcandeleteanobjecttowhichsome

otherobjectstillhasareference.Thatotherreferenceisnow



dangling,meaningitreferstospacethatthesystemconsiders

free.Spacethatisthoughttobefreemightbeallocatedtoa

newobject,andthedanglingreferencewouldthenreference

somethingcompletelydifferentfromwhattheobjectthoughtit

referenced.Thissituationcouldcauseallmannerofhavocwhen

theprogramusesthevaluesinthatspaceasiftheywerepart

ofsomethingtheyarenot.Garbagecollectionsolvesthe

danglingreferenceproblemforyoubecauseanobjectthat'sstill

referencedsomewherewillneverbegarbage-collectedandso

willneverbeconsideredfree.Garbagecollectionalsosolvesthe

problemofaccidentallydeletinganobjectmultiple

timessomethingthatcanalsocausehavoc.

Garbageiscollectedwithoutyourintervention,butcollecting

garbagestilltakeswork.Creatingandcollectinglargenumbers

ofobjectscaninterferewithtime-criticalapplications.You

shoulddesignsuchsystemstobejudiciousinthenumberof

objectstheycreateandsoreducetheamountofgarbagetobe

collected.

Garbagecollectionisnotaguaranteethatmemorywillalways

beavailablefornewobjects.Youcouldcreateobjects

indefinitely,placetheminlists,andcontinuedoingsountil

thereisnomorespaceandnounreferencedobjectstoreclaim.

Youcouldcreateamemoryleakby,forexample,allowingalist

ofobjectstorefertoobjectsyounolongerneed.Garbage

collectionsolvesmany,butnotall,memoryallocationproblems.



17.2.ASimpleModel

Garbagecollectioniseasiertounderstandwithanexplicit

modelsothissectiondescribesasimpleone,butpractical

garbagecollectorsarefarmoresophisticated.Garbage

collectionislogicallysplitintotwophases:separatinglive

objectsfromdeadobjectsandthenreclaimingthestorageof

thedeadones.Liveobjectsarethosethatarereachablefrom

runningcodetheobjectsthatsomeactionofyourcodecanstill

potentiallyuse.Deadobjectsarethegarbagethatcanbe

reclaimed.

Oneobviousmodelofgarbagecollectionisreferencecounting:

WhenobjectXreferencesobjectY,thesystemincrementsa

counteronY,andwhenXdropsitsreferencetoY,thesystem

decrementsthecounter.Whenthecounterreacheszero,Yisno

longerliveandcanbecollected,whichwilldecrementthe

countsofanyotherobjectstowhichYrefers.

Referencecountingfailsinthefaceofcycles,inwhichloopsare

createdinthereferences.IfXandYreferenceeachother,

neitherobject'scounterwilleverbecomezero,andsoneitherX

norYwilleverbecollected,norwillanythingtowhicheither

objectrefers,directlyorindirectly.Mostgarbagecollectorsdo

notusereferencecountingforthisandotherreasons.

Thesimplestmodelofgarbagecollectionnotsubjecttothis

problemiscalledmark-and-sweep.Thenamereferstotheway

thetwophasesofgarbagecollectionareimplemented.Tofind

whichobjectsarelive,thegarbagecollectorfirstdeterminesa

setofrootsthatcontainsthedirectlyreachableobjects:

Referencesinlocalvariablesonthestack,forexample,are

reachablebecauseyoucanusethosevariablestomanipulate

theobject.Objectsreferredtobylocalvariablesaretherefore

clearlylive.



Onceasetofrootsisdetermined,thecollectorwillmarkthe

objectsreferencedbythoserootsasreachable.Itwillthen

examinereferencesineachofthoseobjects.Ifanobject

referredtobysuchareferenceisalreadymarkedreachable

fromthefirststep,itisignored.Otherwise.theobjectis

markedreachableanditsreferencesareexamined.This

processcontinuesuntilnomorereachableobjectsremain

unmarked.Afterthismarkingprocessiscomplete,thecollector

canreclaimthedeadobjects(thosewhicharenotmarked)by

sweepingthemaway.

Anychangetotheinterconnectionofobjectsduringarunof

mark-and-sweepwillclearlyinterferewiththecollection

process.Amarkingruncanmissanobjectthatwas

unreachableatthebeginningofthemarkingprocess,butwhich

isassignedtoareachablereferenceinthemiddle.Runninga

basicmark-and-sweeppassrequiresfreezingexecutionofthe

program,atleastduringthemarkingphase.

Thereareotherproblemswithmark-and-sweep.Garbage

collectionisacomplexareaofresearchwithnoeasyor

universalanswers.Wepresentmark-and-sweepasarelatively

simplementalmodelforyoutousetounderstandgarbage

collection.Eachvirtualmachinehasitsowncollectionstrategy,

andsomeletyouchooseamongseveral.Usethismark-andsweepmodelasamentalmodelonlydonotassumethatthisis

howanyparticularvirtualmachineactuallyworks.



17.3.Finalization

Youwon'tnormallynoticewhenanorphanedobject'sspaceis

reclaimed"itjustworks."Butaclasscanimplementafinalize

methodthatisexecutedbeforeanobject'sspaceis

reclaimedsee"StrengthsofReferenceandReachability"onpage

455.Suchafinalizemethodgivesyouachancetousethestate

containedintheobjecttoreclaimothernon-memoryresources.

ThefinalizemethodisdeclaredintheObjectclass:

protectedvoidfinalize()tHRowsThrowable



Isinvokedbythegarbagecollectorafterit

determinesthatthisobjectisnolongerreachable

anditsspaceistobereclaimed.Thismethodmight

cleanupanynon-memoryresourcesusedbythis

object.Itisinvokedatmostonceperobject,evenif

executionofthismethodcausestheobjectto

becomereachableagainandlateritbecomes

unreachableagain.Thereisnoguarantee,however,

thatfinalizewillbecalledinanyspecifictimeperiod;

itmayneverbecalledatall.Thismethodisdeclared

tothrowanyexceptionbutifanexceptionoccursit

isignoredbythegarbagecollector.Thevirtual

machinemakesnoguaranteesaboutwhichthread

willexecutethefinalizemethodofanygivenobject,

butitdoesguaranteethatthethreadwillnothold

anyuser-visiblesynchronizationlocks.

Youshouldonlyrarelyneedtowriteafinalizemethod,and

whenyoudo,youshouldwriteitwithgreatcare.Ifyourobject

hasbecomegarbageitisquitepossiblethatotherobjectsto

whichitrefersarealsogarbage.Asgarbage,theymayhave

beenfinalizedbeforeyourfinalizemethodisinvokedandmay

thereforebeinanunexpectedstate.



Garbagecollectioncollectsonlymemory.Whenyouaredealing

withnon-memoryresourcesthatarenotreclaimedbygarbage

collection,finalizerslooklikeaneatsolution.Forexample,open

filesareusuallyalimitedresource,soclosingthemwhenyou

canisgoodbehavior.Butthisusuallycannotwaituntilthe

finalizephaseofgarbagecollection.Thecodethatasksyouto

performanoperationthatopensafileshouldtellyouwhenit's

donethereisnoguaranteethatyourobjectholdingtheopenfile

willbecollectedbeforealltheopenfileresourcesareusedup.

Still,yourobjectsthatallocateexternalresourcescouldprovide

afinalizemethodthatcleansthemupsothattheclassdoesn't

itselfcreatearesourceleak.Forexample,aclassthatopensa

filetodoitsworkshouldhavesomeformofclosemethodto

closethefile,enablingprogrammersusingthatclassto

explicitlymanagethenumber-of-open-filesresource.The

finalizemethodcantheninvokeclose.Justdon'trelyonthisto

preventusersoftheclassfromhavingproblems.Theymight

getluckyandhavethefinalizerexecutedbeforetheyrunoutof

openfiles,butthatisriskyfinalizationisasafety-nettobeused

asalastresort,aftertheprogrammerhasfailedtoreleasethe

resourcemanually.Ifyouweretowritesuchamethod,itmight

looklikethis:

publicclassProcessFile{

privateFileReaderfile;

publicProcessFile(Stringpath)throws

FileNotFoundException

{

file=newFileReader(path);

}

//...

publicsynchronizedvoidclose()throwsIOException{

if(file!=null){



file.close();

file=null;

}

}

protectedvoidfinalize()throwsThrowable{

try{

close();

}finally{

super.finalize();

}

}

}



Notethatcloseiscarefullywrittentobecorrectifitisinvoked

morethanonce.Otherwise,ifsomeoneinvokedclose,finalizing

theobjectwouldcauseanothercloseonthefile,whichmight

notbeallowed.

Notealsothat,inthisexample,finalizeinvokessuper.finalizein

afinallyclause.Trainyourselfsothatyoualwayswritethat

invocationinanyfinalizemethodyouwrite.Ifyoudon'tinvoke

super.finalize,youmaycorrectlyfinalizeyourownpartofthe

object,butthesuperclass'spartwillnotgetfinalized.Invoking

super.finalizeisoneofthosegoodhabitsyoushouldadopteven

whenyourclassdoesn'textendanyotherclass.Inadditionto

beinggoodtraining,invokingsuper.finalizeinsuchacasemeans

thatyoucanalwaysaddasuperclasstoaclasslikeProcessFile

withoutrememberingtoexamineitsfinalizemethodfor

correctness.Invokingthesuperclass'sfinalizemethodina

finallyclauseensuresthatthesuperclass'scleanupwillhappen

evenifyourcleanupcausesanexception.

Thegarbagecollectormayreclaimobjectsinanyorderorit

mayneverreclaimthem.Memoryresourcesarereclaimedwhen



thegarbagecollectorthinksthetimeisappropriate.Notbeing

boundtoanorderingguarantee,thegarbagecollectorcan

operateinwhatevermannerismostefficient,andthathelps

minimizetheoverheadofgarbagecollection.Youcan,if

necessary,invokethegarbagecollectortotrytoforceearlier

collectionusingSystem.gcorRuntime.gc,asyou'llseeinthenext

section,butthereisnoguaranteethatgarbagecollectionwill

actuallyoccur.

Whenanapplicationexits,nofurthergarbagecollectionis

performed,soanyobjectsthathavenotyetbeencollectedwill

nothavetheirfinalizemethodsinvoked.Inmanycasesthiswill

notbeaproblem.Forexample,onmostsystemswhenthe

virtualmachineexits,theunderlyingsystemautomatically

closesallopenfilesandsockets.However,fornon-system

resourcesyouwillhavetoinventothersolutions.(Temporary

filescanbemarkedas"deleteonexit,"whichsolvesoneofthe

morecommonissuessee"TheFileClass"onpage543.)

Referencequeuesdiscussedonpage459provideabetterwayof

performingclean-upactionswhenanobjectisitabouttobe,or

hasbeen,reclaimed.



17.3.1.ResurrectingObjectsduringfinalize

Afinalizemethodcan"resurrect"anobjectbymakingit

referencedagainforexample,byaddingittoastaticlistof

objects.Resurrectionisdiscouraged,butthereisnothingthe

systemcandotostopyou.

However,thevirtualmachineinvokesfinalizeatmostonceon

anyobject,evenifthatobjectbecomesunreachablemorethan

oncebecauseapreviousfinalizeresurrectedit.Ifresurrecting

objectsisimportanttoyourdesign,theobjectwouldbe

resurrectedonlyonceprobablynotthebehavioryouwanted.



Ifyouthinkyouneedtoresurrectobjects,youshouldreview

yourdesigncarefullyyoumayuncoveraflaw.Ifyourdesign

reviewconvincesyouthatyouneedsomethinglikeresurrection,

thebestsolutionistoclonetheobjectorcreateanewobject,

nottoresurrectit.Thefinalizemethodcaninsertareferenceto

anewobjectthatwillcontinuethestateofthedyingobject

ratherthanareferencetothedyingobjectitself.Beingnew,the

clonedobject'sfinalizemethodwillbeinvokedinthefuture(if

needed),enablingittoinsertyetanothercopyofitselfinyet

anotherlist,ensuringthesurvival,ifnotofitself,atleastofits

progeny.



17.4.InteractingwiththeGarbageCollector

Althoughthelanguagehasnoexplicitwaytodisposeof

unwantedobjects,youcandirectlyinvokethegarbagecollector

tolookforunusedobjects.TheRuntimeclass,togetherwithsome

conveniencemethodsintheSystemclass,allowsyoutoinvoke

thegarbagecollector,requestthatanypendingfinalizersbe

run,orquerythecurrentmemorystate:

publicvoidgc()



Asksthevirtualmachinetoexpendefforttoward

recyclingunusedobjectssothattheirmemorycan

bereused.

publicvoidrunFinalization()



Asksthevirtualmachinetoexpendeffortrunning

thefinalizersofobjectsthatithasfoundtobe

unreachablebuthavenotyethadtheirfinalizers

run.

publiclongfreeMemory()



Returnsanestimateoffreebytesinsystem

memory.

publiclongtotalMemory()



Returnsthetotalbytesinsystemmemory.

publiclongmaxMemory()



Returnsthemaximumamountofmemory,inbytes,

thatthevirtualmachinewilleverattempttouse.If

thereisnolimit,Long.MAX_VALUEisreturned.Thereis

nomethodtosetthemaximum;avirtualmachine

willtypicallyhaveacommand-lineorother

configurationoptiontosetthemaximum.

Toinvokethesemethodsyouneedtoobtainareferencetothe

currentRuntimeobjectviathestaticmethodRuntime.getRuntime.

TheSystemclasssupportsstaticgcandrunFinalizationmethods

thatinvokethecorrespondingmethodsonthecurrentRuntime;

inotherwords,System.gc()isequivalentto

Runtime.getRuntime().gc().

Thegarbagecollectormaynotbeabletofreeanyadditional

memorywhenRuntime.gcisinvoked.Theremaybenogarbageto

collect,andnotallgarbagecollectorscanfindcollectable

objectsondemand.Soinvokingthegarbagecollectormayhave

noeffectwhatsoever.However,beforecreatingalargenumber

ofobjectsespeciallyinatime-criticalapplicationthatmightbe

affectedbygarbage-collectionoverheadinvokinggcmaybe

advisable.Doingsohastwopotentialbenefits:Youstartwithas

muchfreememoryaspossible,andyoureducethelikelihoodof

thegarbagecollectorrunningduringthetask.Hereisamethod

thataggressivelyfreeseverythingitcanatthemoment:

publicstaticvoidfullGC(){

Runtimert=Runtime.getRuntime();

longisFree=rt.freeMemory();

longwasFree;

do{

wasFree=isFree;

rt.runFinalization();

rt.gc();

isFree=rt.freeMemory();

}while(isFree>wasFree);

}



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 17. Garbage Collection and Memory

Tải bản đầy đủ ngay(0 tr)

×