计算机科学与技术Java垃圾收集器中英文对照外文翻译文献_第1页
计算机科学与技术Java垃圾收集器中英文对照外文翻译文献_第2页
计算机科学与技术Java垃圾收集器中英文对照外文翻译文献_第3页
计算机科学与技术Java垃圾收集器中英文对照外文翻译文献_第4页
计算机科学与技术Java垃圾收集器中英文对照外文翻译文献_第5页
已阅读5页,还剩9页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

中英文资料中英文资料外文翻译文献原文:HowagarbagecollectorworksofJavaLanguageIfyoucomefromaprogramminglanguagewhereallocatingobjectsontheheapisexpensive,youmaynaturallyassumethatJava’sschemeofallocatingeverything(exceptprimitives)ontheheapisalsoexpensive.However,itturnsoutthatthegarbagecollectorcanhaveasignificantimpactonincreasingthespeedofobjectcreation.Thismightsoundabitoddatfirst—thatstoragereleaseaffectsstorageallocation—butit’sthewaysomeJVMswork,anditmeansthatallocatingstorageforheapobjectsinJavacanbenearlyasfastascreatingstorageonthestackinotherlanguages.Forexample,youcanthinkoftheC++heapasayardwhereeachstakesoutitsownpieceofturfobject.Thisrealestatecanbecomeabandonedsometimelaterandmustbereused.InsomeJVMs,theJavaheapisquitedifferent;it’smorelikeaconveyorbeltthatmovesforwardeverytimeyouallocateanewobject.Thismeansthatobjectstorageallocationisremarkablyrapid.The“heappointer”issimplymovedforwardintovirginterritory,soit’seffectivelythesameasC++’sstackallocation.(Ofcourse,there’salittleextraoverheadforbookkeeping,butit’snothinglikesearchingforstorage.)Youmightobservethattheheapisn’tinfactaconveyorbelt,andifyoutreatitthatway,you’llstartpagingmemory—movingitonandoffdisk,sothatyoucanappeartohavemorememorythanyouactuallydo.Pagingsignificantlyimpactsperformance.Eventually,afteryoucreateenoughobjects,you’llrunoutofmemory.Thetrickisthatthegarbagecollectorstepsin,andwhileitcollectsthegarbageitcompactsalltheobjectsintheheapsothatyou’veeffectivelymovedthe“heappointer”closertothebeginningoftheconveyorbeltandfartherawayfromapagefault.Thegarbagecollectorrearrangesthingsandmakesitpossibleforthehigh-speed,infinite-free-heapmodeltobeusedwhileallocatingstorage.TounderstandgarbagecollectioninJava,it’shelpfullearnhowgarbage-collectionschemesworkinothersystems.Asimplebutslowgarbage-collectiontechniqueiscalledreferencecounting.Thismeansthateachobjectcontainsareferencecounter,andeverytimeareferenceisattachedtothatobject,thereferencecountisincreased.Everytimeareferencegoesoutofscopeorissettonull,thereferencecountisdecreased.Thus,managingreferencecountsisasmallbutconstantoverheadthathappensthroughoutthelifetimeofyourprogram.Thegarbagecollectormovesthroughtheentirelistofobjects,andwhenitfindsonewithareferencecountofzeroitreleasesthatstorage(however,referencecountingschemesoftenreleaseanobjectassoonasthecountgoestozero).Theonedrawbackisthatifobjectscircularlyrefertoeachothertheycanhavenonzeroreferencecountswhilestillbeinggarbage.Locatingsuchself-referentialgroupsrequiressignificantextraworkforthegarbagecollector.Referencecountingiscommonlyusedtoexplainonekindofgarbagecollection,butitdoesn’tseemtobeusedinanyJVMimplementations.Infasterschemes,garbagecollectionisnotbasedonreferencecounting.Instead,itisbasedontheideathatanynon-deadobjectmustultimatelybetraceablebacktoareferencethatliveseitheronthestackorinstaticstorage.Thechainmightgothroughseverallayersofobjects.Thus,ifyoustartinthestackandinthestaticstorageareaandwalkthroughallthereferences,you’llfindalltheliveobjects.Foreachreferencethatyoufind,youmusttraceintotheobjectthatitpointstoandthenfollowallthereferencesinthatobject,tracingintotheobjectstheypointto,etc.,untilyou’vemovedthroughtheentireWebthatoriginatedwiththereferenceonthestackorinstaticstorage.Eachobjectthatyoumovethroughmuststillbealive.Notethatthereisnoproblemwithdetachedself-referentialgroups—thesearesimplynotfound,andarethereforeautomaticallygarbage.Intheapproachdescribedhere,theJVMusesanadaptivegarbage-collectionscheme,andwhatitdoeswiththeliveobjectsthatitlocatesdependsonthevariantcurrentlybeingused.Oneofthesevariantsisstop-and-copy.Thismeansthat—forreasonsthatwillbecomeapparent—theprogramisfirststopped(thisisnotabackgroundcollectionscheme).Then,eachliveobjectiscopiedfromoneheaptoanother,leavingbehindallthegarbage.Inaddition,astheobjectsarecopiedintothenewheap,theyarepackedend-to-end,thuscompactingthenewheap(andallowingnewstoragetosimplybereeledofftheendaspreviouslydescribed).Ofcourse,whenanobjectismovedfromoneplacetoanother,allreferencesthatpointattheobjectmustbechanged.Thereferencethatgoesfromtheheaporthestaticstorageareatotheobjectcanbechangedrightaway,buttherecanbeotherreferencespointingtothisobjectInitialization&Cleanupthatwillbeencounteredlaterduringthe“walk.”Thesearefixedupastheyarefound(youcouldimagineatablethatmapsoldaddressestonewones).Therearetwoissuesthatmaketheseso-called“copycollectors”inefficient.Thefirstistheideathatyouhavetwoheapsandyousloshallthememorybackandforthbetweenthesetwoseparateheaps,maintainingtwiceasmuchmemoryasyouactuallyneed.SomeJVMsdealwiththisbyallocatingtheheapinchunksasneededandsimplycopyingfromonechunktoanother.Thesecondissueisthecopyingprocessitself.Onceyourprogrambecomesstable,itmightbegeneratinglittleornogarbage.Despitethat,acopycollectorwillstillcopyallthememoryfromoneplacetoanother,whichiswasteful.Topreventthis,someJVMsdetectthatnonewgarbageisbeinggeneratedandswitchtoadifferentscheme(thisisthe“adaptive”part).Thisotherschemeiscalledmark-and-sweep,andit’swhatearlierversionsofSun’sJVMusedallthetime.Forgeneraluse,mark-and-sweepisfairlyslow,butwhenyouknowyou’regeneratinglittleornogarbage,it’sfast.Mark-and-sweepfollowsthesamelogicofstartingfromthestackandstaticstorage,andtracingthroughallthereferencestofindliveobjects.However,eachtimeitfindsaliveobject,thatobjectismarkedbysettingaflaginit,buttheobjectisn’tcollectedyet.Onlywhenthemarkingprocessisfinisheddoesthesweepoccur.Duringthesweep,thedeadobjectsarereleased.However,nocopyinghappens,soifthecollectorchoosestocompactafragmentedheap,itdoessobyshufflingobjectsaround.“Stop-and-copy”referstotheideathatthistypeofgarbagecollectionisnotdoneinthebackground;Instead,theprogramisstoppedwhilethegarbagecollectionoccurs.IntheSunliteratureyou’llfindmanyreferencestogarbagecollectionasalow-prioritybackgroundprocess,butitturnsoutthatthegarbagecollectionwasnotimplementedthatwayinearlierversionsoftheSunJVM.Instead,theSungarbagecollectorstoppedtheprogramwhenmemorygotlow.Mark-and-sweepalsorequiresthattheprogrambestopped.Aspreviouslymentioned,intheJVMdescribedherememoryisallocatedinbigblocks.Ifyouallocatealargeobject,itgetsitsownblock.Strictstop-and-copyrequirescopyingeveryliveobjectfromthesourceheaptoanewheapbeforeyoucanfreetheoldone,whichtranslatestolotsofmemory.Withblocks,thegarbagecollectioncantypicallycopyobjectstodeadblocksasitcollects.Eachblockhasagenerationcounttokeeptrackofwhetherit’salive.Inthenormalcase,onlytheblockscreatedsincethelastgarbagecollectionarecompacted;allotherblocksgettheirgenerationcountbumpediftheyhavebeenreferencedfromsomewhere.Thishandlesthenormalcaseoflotsofshort-livedtemporaryobjects.Periodically,afullsweepismade—largeobjectsarestillnotcopied(theyjustgettheirgenerationcountbumped),andblockscontainingsmallobjectsarecopiedandcompacted.TheJVMmonitorstheefficiencyofgarbagecollectionandifitbecomesawasteoftimebecauseallobjectsarelong-lived,thenitswitchestomark-andsweep.Similarly,theJVMkeepstrackofhowsuccessfulmark-and-sweepis,andiftheheapstartstobecomefragmented,itswitchesbacktostop-and-copy.Thisiswherethe“adaptive”partcomesin,soyouendupwithamouthful:“Adaptivegenerationalstop-and-copymark-andsweep.”ThereareanumberofadditionalspeedupspossibleinaJVM.Anespeciallyimportantoneinvolvestheoperationoftheloaderandwhatiscalledajust-in-time(JIT)compiler.AJITcompilerpartiallyorfullyconvertsaprogramintonativemachinecodesothatitdoesn’tneedtobeinterpretedbytheJVMandthusrunsmuchfaster.Whenaclassmustbeloaded(typically,thefirsttimeyouwanttocreateanobjectofthatclass),the.classfileislocated,andthebytecodesforthatclassarebroughtintomemory.Atthispoint,oneapproachistosimplyJITcompileallthecode,butthishastwodrawbacks:Ittakesalittlemoretime,which,compoundedthroughoutthelifeoftheprogram,canaddup;anditincreasesthesizeoftheexecutable(bytecodesaresignificantlymorecompactthanexpandedJITcode),andthismightcausepaging,whichdefinitelyslowsdownaprogram.Analternativeapproachislazyevaluation,whichmeansthatthecodeisnotJITcompileduntilnecessary.Thus,codethatnevergetsexecutedmightneverbeJITcompiled.TheJavaHotspottechnologiesinrecentJDKstakeasimilarapproachbyincreasinglyoptimizingapieceofcodeeachtimeitisexecuted,sothemorethecodeisexecuted,thefasteritgets.译文:Java垃圾收集器的工作方式如果你学下过一种因为在堆里分配对象所以开销过大的编程语言,很自然你可能会假定Java在堆里为每一样东西(除了primitives)分配内存资源的机制开销也会很大。不过,事实上垃圾收集器能够深刻影响对象的加速创建。一开始听起来有些奇怪——存贮空间的释放会影响存贮空间的分配,但是这的确是一些JVMs的工作方式,并且这意味着Java为堆对象分配存贮空间几乎和别的语言里为栈分配存贮空间一样地快。举个例子,你可以认为C++的堆就如同一个堆放的工场,在这个工场里,每一个对象都立有的地皮占有权不久会被废除无效,并且这块地皮必须重新加以利用。在Java的JVM里,堆的工作方式完全不同;每次为一个新的对象分配存贮空间的时候,它就更像是一个不断向前移动的传送带。这就意味着对象存贮空间的分配速度明显加快。在这个过程中,“堆指针”简单地向还没被占用的空间领域移动,所以非常像C++里栈的分配方式。(当然,记录工作会有一点额外的开销,但是完全不同于C++里那种在堆放工场里为寻找没被利用的存贮空间而付出的开销。)你或许观察到实际上堆本身并不是一个传送带,如果你真的那样看待堆,你就会启用虚拟内存——在硬盘里不断地装卸,结果是看上去你会拥有比实际情况还要多的内存空间。最终,当你创建了足够多的对象后,你会耗尽内存。Java的诀窍就在于垃圾搜集器插手于其中,当垃圾收集器收集垃圾的时候,它会压缩所有堆里的对象以便你能够有效的将堆指针移动到相应的地方从而远离了页面错误。垃圾收集器重新安排了整个过程,这使得分配存贮空间的时候一种高速,无穷闲置的堆模式成为可能。要想理解Java的垃圾收集工作,先了解一下别的语言系统里垃圾收集所使用的方案是有帮助的。一种简单的但却较慢的垃圾收集技术就是引用记数(referencecounting)。这种技术意味着每个对象都含有一个引用计数器,每一次一个引用指向那个对象的时候,引用记数就增加1每一次对象引用离开作用域或者被设置为null的时候,引用记数就减1。因此,应付对象被引用的数量在你的程序的整个生命周期里是一笔较小但却一直持续的开销。垃圾收集器历遍整组对象,当它发现一个引用记数为零的对象时就会释放那个对象的存贮空间。(不过,只要记数为零,引用记数方案通常会立刻释放对象)。这种方案的一个缺点是如果对象之间循环着互相引用,那么这些对象的引用记数可能为非零,而垃圾收集器依然把它们当作垃圾收集。定位这种自我引用的对象组需要垃圾收集器付出大量额外的工作。引用记数通常被用来解释一类垃圾收集的工作原理,但是它似乎没被任何一种JVM所采纳。有一种执行更快的垃圾收集方案,这种方案中垃圾收集不是建立在引用记数的基础上。相反,它的思想是任何没死的对象最终一定会在栈和静态存贮器里找到相应存活的引用。这种链式的查找方式可能历遍几个层次的对象组。因此,如果从栈和静态存贮器里开始并历遍整个引用组,你会找到所有存活的对象。对于你找到的每个单引用,你必须找到它所指向的对象,然后发觉那个对象的所有引用,接着找到那些引用所指向的所有对象,依次类推,直到你历遍整个由栈和静态存贮器里的引用所形成的网。每个你找到的对象必须还存活着。注意,这里不存在分离的自我引用的对象组——他们只是没被查找到,因此被自动当作垃圾。在上述提到的垃圾收集方案中,JVM使用了一种自适应的垃圾收集方案,它对查找到的存活对象采取的措施依赖于它正在使用的方案变体。其中的一个变体就是stop-and-copy。它意味着——基于一些明显的原因——程序首先停止运行(这不是一种在后台实施的垃圾收集方案)。然后,每一个活着的对象从一个堆里被拷贝到另一个堆里,同时被拷贝的活对象和死的对象被当作垃圾遗弃。并且,当对象被拷贝到新的堆里后,他们在那里被一个挨一个塞紧,因此实现了压缩新堆的目的(而且如前所述,这种方式腾出了压缩后多余出来的新的空间)。当然,对象从一个地方移动到另一个地方的时候,所有指向对象的引用必须相应改变。指向堆或者静态存贮器里某个被移动对象的引用可以立即得到改变,但是还存在其它后来“在走走”的时候才会碰到的指向该对象的引用。这些引用一旦发现就会被修改。(你可以想象存在一张映射旧新地址的表)。有两个问题使这种所谓的“拷贝型收集器”缺乏效率。第一个问题就是你使用了两个堆,为了维护两倍于你实际所需要的内存空间,你得在这两个堆之间来回搅动着整个内存空间。一些JVMs通过依据实际所需来为堆分配大块内存,然后很简单地从一个块拷贝对象到另一个。第二个问题是拷贝过程本身。一旦你地程序趋向于稳定的时候,它可能生成很少或者几乎不生成垃圾。然而stop-and-copy方案不管这些,拷贝型垃圾收集器依旧把活对象占用的空间从一个地方拷贝到另一个地方,这就形成了浪费。为了阻止这种情况的发生,一些JVMs会探测没有新垃圾产生的时机,并且会转向实施另外一个完全不同的垃圾收集方案。这种不同的方案被称为mark-and-sweep,并且它是Sun的早期JVM版本一直使用的方案。处理一般的垃圾收集工作,mark-and-sweep表现得相当地慢,但是当你的程序生成很少或者不生成垃圾时,它又运行得很快。Mark-and-sweep遵循着和stop-and-copy一样的逻辑:从栈和静态存贮器里出发,跟踪所有的引用从而找到存活的对象。不过,每次它找到活对象的时候,那个对象被做以标记,而且对象还不会被收集起来。只有在整个标记过程完成后,清扫(sweep)工作才真正

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论