Stack Memory and Heap Space in Java - Baeldung

文章推薦指數: 80 %
投票人數:10人

Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, ... StartHereCourses ▼▲ RESTwithSpring ThecanonicalreferenceforbuildingaproductiongradeAPIwithSpring LearnSpringSecurity ▼▲ THEuniqueSpringSecurityeducationifyou’reworkingwithJavatoday LearnSpringSecurityCore FocusontheCoreofSpringSecurity5 LearnSpringSecurityOAuth FocusonthenewOAuth2stackinSpringSecurity5 LearnSpring Fromnoexperiencetoactuallybuildingstuff​ LearnSpringDataJPA ThefullguidetopersistencewithSpringDataJPA Guides ▼▲ Persistence ThePersistencewithSpringguides REST TheguidesonbuildingRESTAPIswithSpring Security TheSpringSecurityguides About ▼▲ FullArchive Thehighleveloverviewofallthearticlesonthesite. BaeldungEbooks DiscoverallofoureBooks WriteaboutLinux BecomeawriteronthesiteintheLinuxarea AboutBaeldung AboutBaeldung. JavaTop GetstartedwithSpring5andSpringBoot2,throughtheLearnSpringcourse: >CHECKOUTTHECOURSE 1.Introduction Torunanapplicationinanoptimalway,JVMdividesmemoryintostackandheapmemory.Wheneverwedeclarenewvariablesandobjects,callanewmethod,declareaString,orperformsimilaroperations,JVMdesignatesmemorytotheseoperationsfromeitherStackMemoryorHeapSpace. Inthistutorial,we'llexaminethesememorymodels.First,we'llexploretheirkeyfeatures.Thenwe'lllearnhowtheyarestoredinRAM,andwheretousethem.Finally,we'lldiscussthekeydifferencesbetweenthem. 2.StackMemoryinJava StackMemoryinJavaisusedforstaticmemoryallocationandtheexecutionofathread.Itcontainsprimitivevaluesthatarespecifictoamethodandreferencestoobjectsreferredfromthemethodthatareinaheap. AccesstothismemoryisinLast-In-First-Out(LIFO)order.Wheneverwecallanewmethod,anewblockiscreatedontopofthestackwhichcontainsvaluesspecifictothatmethod,likeprimitivevariablesandreferencestoobjects. Whenthemethodfinishesexecution,itscorrespondingstackframeisflushed,theflowgoesbacktothecallingmethod,andspacebecomesavailableforthenextmethod. 2.1.KeyFeaturesofStackMemory Someotherfeaturesofstackmemoryinclude: Itgrowsandshrinksasnewmethodsarecalledandreturned,respectively. Variablesinsidethestackexistonlyaslongasthemethodthatcreatedthemisrunning. It'sautomaticallyallocatedanddeallocatedwhenthemethodfinishesexecution. Ifthismemoryisfull,Javathrowsjava.lang.StackOverFlowError. Accesstothismemoryisfastwhencomparedtoheapmemory. Thismemoryisthreadsafe,aseachthreadoperatesinitsownstack. 3.HeapSpaceinJava HeapspaceisusedforthedynamicmemoryallocationofJavaobjectsandJREclassesatruntime.Newobjectsarealwayscreatedinheapspace,andthereferencestotheseobjectsarestoredinstackmemory. Theseobjectshaveglobalaccessandwecanaccessthemfromanywhereintheapplication. Wecanbreakthismemorymodeldownintosmallerparts,calledgenerations,whichare: YoungGeneration–thisiswhereallnewobjectsareallocatedandaged.AminorGarbagecollectionoccurswhenthisfillsup. OldorTenuredGeneration–thisiswherelongsurvivingobjectsarestored.WhenobjectsarestoredintheYoungGeneration,athresholdfortheobject'sageisset,andwhenthatthresholdisreached,theobjectismovedtotheoldgeneration. PermanentGeneration–thisconsistsofJVMmetadatafortheruntimeclassesandapplicationmethods. ThesedifferentportionsarealsodiscussedinthearticleDifferenceBetweenJVM,JRE,andJDK. Wecanalwaysmanipulatethesizeofheapmemoryasperourrequirement.Formoreinformation,visitthislinkedBaeldungarticle. 3.1.KeyFeaturesofJavaHeapMemory Someotherfeaturesofheapspaceinclude: It'saccessedviacomplexmemorymanagementtechniquesthatincludetheYoungGeneration,OldorTenuredGeneration,andPermanentGeneration. Ifheapspaceisfull,Javathrows java.lang.OutOfMemoryError. Accesstothismemoryiscomparativelyslowerthanstackmemory Thismemory,incontrasttostack,isn'tautomaticallydeallocated.ItneedsGarbageCollectortofreeupunusedobjectssoastokeeptheefficiencyofthememoryusage. Unlikestack,aheapisn'tthreadsafeandneedstobeguardedbyproperlysynchronizingthecode. 4.Example Basedonwhatwe'velearnedsofar,let'sanalyzeasimpleJavacodetoassesshowtomanagememoryhere: classPerson{ intid; Stringname; publicPerson(intid,Stringname){ this.id=id; this.name=name; } } publicclassPersonBuilder{ privatestaticPersonbuildPerson(intid,Stringname){ returnnewPerson(id,name); } publicstaticvoidmain(String[]args){ intid=23; Stringname="John"; Personperson=null; person=buildPerson(id,name); } } Let'sanalyzethisstep-by-step: Whenweenterthemain()method,aspaceinstackmemoryiscreatedtostoreprimitivesandreferencesofthismethod. Stackmemorydirectlystorestheprimitivevalueofintegerid. Thereference variableperson oftypePerson willalsobecreatedinstackmemory,whichwillpointtotheactualobjectintheheap. Thecalltotheparameterizedconstructor Person(int,String)frommain() willallocatefurthermemoryontopofthepreviousstack.Thiswillstore: Thethisobjectreferenceofthecallingobjectinstackmemory Theprimitivevalue id inthestackmemory ThereferencevariableofStringargumentname,whichwillpointtotheactualstringfromstringpoolinheapmemory ThemainmethodisfurthercallingthebuildPerson()staticmethod,forwhichfurtherallocationwilltakeplaceinstackmemoryontopofthepreviousone.Thiswillagainstorevariablesinthemannerdescribedabove. However,heapmemorywillstoreallinstancevariablesforthenewlycreatedobjectpersonoftype Person. Let'slookatthisallocationinthediagrambelow: 5.Summary Beforeweconcludethisarticle,let'squicklysummarizethedifferencesbetweentheStackMemoryandtheHeapSpace: Parameter StackMemory HeapSpace Application Stackisusedinparts,oneatatimeduringexecutionofathread TheentireapplicationusesHeapspaceduringruntime Size StackhassizelimitsdependinguponOS,andisusuallysmallerthanHeap ThereisnosizelimitonHeap Storage StoresonlyprimitivevariablesandreferencestoobjectsthatarecreatedinHeapSpace Allthenewlycreatedobjectsarestoredhere Order It'saccessedusingLast-inFirst-out(LIFO)memoryallocationsystem Thismemoryisaccessedviacomplexmemorymanagementtechniquesthatinclude YoungGeneration,OldorTenuredGeneration,andPermanentGeneration. Life Stackmemoryonlyexistsaslongasthecurrentmethodisrunning Heapspaceexistsaslongastheapplicationruns Efficiency Muchfastertoallocatewhencomparedtoheap Slowertoallocatewhencomparedtostack Allocation/Deallocation ThisMemoryisautomaticallyallocatedanddeallocatedwhenamethodiscalledandreturned,respectively HeapspaceisallocatedwhennewobjectsarecreatedanddeallocatedbyGargabeCollectorwhenthey'renolongerreferenced 6.Conclusion StackandheaparetwowaysinwhichJavaallocatesmemory.Inthisarticle,welearnedhowtheywork,andwhentousethemfordevelopingbetterJavaprograms. TolearnmoreaboutMemoryManagementinJava,havealookatthisarticlehere.WealsotouchedontheJVMGarbageCollector,whichisdiscussedbrieflyoverinthisarticle. Javabottom GetstartedwithSpring5andSpringBoot2,throughtheLearnSpringcourse: >>CHECKOUTTHECOURSE Genericfooterbanner LearningtobuildyourAPIwithSpring? DownloadtheE-book 2Comments Oldest Newest InlineFeedbacks Viewallcomments ViewComments LoadMoreComments Commentsareclosedonthisarticle! Javasidebarbanner BuildingaRESTAPIwithSpring5? DownloadtheE-book wpDiscuzInsert Followthe Java Category FollowtheJavacategorytogetregularinfoaboutthenewarticlesandtutorialswepublishhere. FOLLOWTHEJAVACATEGORY



請為這篇文章評分?