资源描述:
《Java之垃圾回收》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、FinalizationandGarbageCollectionInJavaProgrammersknowabouttheimportanceofinitialization,butoftenforgettheimportanceofcleanup.Afterall,whoneedstocleanupanint?Butwithlibraries,simply“lettinggo”ofanobjectonceyou’redonewithitisnotalwayssafe.Ofcourse,Javahasthegarbagecollectortore
2、claimthememoryofobjectsthatarenolongerused.Nowconsideranunusualcase:Supposeyourobjectallocates“special”memorywithoutusingnew.Thegarbagecollectoronlyknowshowtoreleasememoryallocatedwithnew,soitwon’tknowhowtoreleasetheobject’s“special”memory.Tohandlethiscase,Javaprovidesamethod
3、calledfinalize()thatyoucandefineforyourclass.Here’showit’ssupposedtowork.Whenthegarbagecollectorisreadytoreleasethestorageusedforyourobject,itwillfirstcallfinalize(),andonlyonthenextgarbage-collectionpasswillitreclaimtheobject’smemory.Soifyouchoosetousefinalize(),itgivesyouth
4、eabilitytoperformsomeimportantcleanupatthetimeofgarbagecollection.Thisisapotentialprogrammingpitfallbecausesomeprogrammers,especiallyC++programmers,mightinitiallymistakefinalize()forthedestructorinC++,whichisafunctionthatisalwayscalledwhenanobjectisdestroyed.Itisimportanttodi
5、stinguishbetweenC++andJavahere,becauseinC++,objectsalwaysgetdestroyed(inabug-freeprogram),whereasinJava,objectsdonotalwaysgetgarbagecollected.Or,putanotherway:1.Yourobjectsmightnotgetgarbagecollected.2.Garbagecollectionisnotdestruction.Ifyourememberthis,youwillstayoutoftroubl
6、e.Whatitmeansisthatifthereissomeactivitythatmustbeperformedbeforeyounolongerneedanobject,youmustperformthatactivityyourself.Javahasnodestructororsimilarconcept,soyoumustcreateanordinarymethodtoperformthiscleanup.Forexample,supposethatintheprocessofcreatingyourobject,itdrawsit
7、selfonthescreen.Ifyoudon’texplicitlyeraseitsimagefromthescreen,itmightnevergetcleanedup.Ifyouputsomekindoferasingfunctionalityinsidefinalize(),thenifanobjectisgarbagecollectedandfinalize()iscalled(andthere’snoguaranteethiswillhappen),thentheimagewillfirstberemovedfromthescree
8、n,butifitisn’t,theimagewillremain.12/12Youmightfindthatthestoragefor