Stack Memory and Heap Space in Java - Baeldung
文章推薦指數: 80 %
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
延伸文章資訊
- 1在Java 中增加堆空間| D棧
Java Heap. 創建時間: April-26, 2022. 使用命令列增加Java 堆大小; 在整合開發環境(IDE) 中增加Java 堆大小. 在Java 中,堆空間主要用於垃圾收集和為...
- 2stack 和heap | 新手Java 工程師的學習筆記 - - 點部落
heap. 1.可動態申請之內存空間. 2.java中new XXX() 物件全部會放到heap中 一旦garbage collection system偵測到某對象沒被引用就會銷毀此物件.
- 3Java - Stack 與Heap 的分別 - iT 邦幫忙
閱讀時間: 10分鐘. 在使用Java開發程式的過程中,相信大家都可能見過stack和heap這兩個字,例如在一些Error中、在JVM中做一些設定(heap memory space跟stac...
- 4Determining the Java heap memory size - IBM
The Java heap is memory that contains objects used by Java programs. It contains objects that are...
- 5java.lang.OutOfMemoryError Java heap space? 怎麼解?
前言因為工作關係,其實不只會碰到node.js有時候還會協助其他專案,而有的專案就是用java 寫的很久之前在伺服器噴出一個OutOfMemoryError: Java heap ...