Stack Vs Heap Java - Javatpoint
文章推薦指數: 80 %
The major difference between Stack memory and heap memory is that the stack is used to store the order of method execution and local variables while the heap ... ⇧SCROLLTOTOP Home Java Programs OOPs String Exception Multithreading Collections JavaFX JSP Spring SpringBoot Projects InterviewQuestions JavaTutorial WhatisJava HistoryofJava FeaturesofJava C++vsJava HelloJavaProgram ProgramInternal Howtosetpath? JDK,JREandJVM JVM:JavaVirtualMachine JavaVariables JavaDataTypes UnicodeSystem Operators Keywords ControlStatements JavaControlStatements JavaIf-else JavaSwitch JavaForLoop JavaWhileLoop JavaDoWhileLoop JavaBreak JavaContinue JavaComments JavaPrograms JavaObjectClass JavaOOPsConcepts NamingConvention ObjectandClass Method Constructor statickeyword thiskeyword JavaInheritance Inheritance(IS-A) Aggregation(HAS-A) JavaPolymorphism MethodOverloading MethodOverriding CovariantReturnType superkeyword InstanceInitializerblock finalkeyword RuntimePolymorphism DynamicBinding instanceofoperator JavaAbstraction Abstractclass Interface AbstractvsInterface JavaEncapsulation Package AccessModifiers Encapsulation JavaArray JavaArray JavaOOPsMisc Objectclass ObjectCloning Mathclass WrapperClass JavaRecursion CallByValue strictfpkeyword javadoctool CommandLineArg ObjectvsClass OverloadingvsOverriding JavaString JavaRegex ExceptionHandling JavaInnerclasses JavaMultithreading JavaI/O JavaNetworking JavaAWT&Events JavaSwing JavaFX JavaApplet JavaReflection JavaDate JavaConversion JavaCollection JavaJDBC JavaMisc JavaNewFeatures RMI Internationalization InterviewQuestions JavaMCQ next→ ←prev StackVsHeapJava InJava,memorymanagementisavitalprocess.ItismanagedbyJavaautomatically.TheJVMdividesthememoryintotwoparts:stackmemoryandheapmemory.FromtheperspectiveofJava,bothareimportantmemoryareasbutbothareusedfordifferentpurposes.ThemajordifferencebetweenStackmemoryandheapmemoryisthatthestackisusedtostoretheorderofmethodexecutionandlocalvariableswhiletheheapmemorystorestheobjectsanditusesdynamicmemoryallocationanddeallocation.Inthissection,wewilldiscussthedifferencesbetweenstackandheapindetail. StackMemory Thestackmemoryisaphysicalspace(inRAM)allocatedtoeachthreadatruntime.Itiscreatedwhenathreadcreates.MemorymanagementinthestackfollowsLIFO(Last-In-First-Out)orderbecauseitisaccessibleglobally.Itstoresthevariables,referencestoobjects,andpartialresults.Memoryallocatedtostacklivesuntilthefunctionreturns.Ifthereisnospaceforcreatingthenewobjects,itthrowsthejava.lang.StackOverFlowError.Thescopeoftheelementsislimitedtotheirthreads.TheJVMcreatesaseparatestackforeachthread. HeapMemory ItiscreatedwhentheJVMstartsupandusedbytheapplicationaslongastheapplicationruns.ItstoresobjectsandJREclasses.Wheneverwecreateobjectsitoccupiesspaceintheheapmemorywhilethereferenceofthatobjectcreatesinthestack.Itdoesnotfollowanyorderlikethestack.Itdynamicallyhandlesthememoryblocks.Itmeans,weneednottohandlethememorymanually.Formanagingthememoryautomatically,Javaprovidesthegarbagecollectorthatdeletestheobjectswhicharenolongerbeingused.Memoryallocatedtoheaplivesuntilanyoneevent,eitherprogramterminatedormemoryfreedoesnotoccur.Theelementsaregloballyaccessibleintheapplication.Itisacommonmemoryspacesharedwithallthethreads.Iftheheapspaceisfull,itthrowsthejava.lang.OutOfMemoryError.Theheapmemoryisfurtherdividedintothefollowingmemoryareas: Younggeneration Survivorspace Oldgeneration Permanentgeneration CodeCache Thefollowingimageshowstheallocationofstackmemoryandheapspace. DifferenceBetweenStackandHeapMemory Thefollowingtablesummarizesallthemajordifferencesbetweenstackmemoryandheapspace. Parameter StackMemory HeapSpace Application Itstoresitemsthathaveaveryshortlifesuchasmethods,variables,andreferencevariablesoftheobjects. ItstoresobjectsandJavaRuntimeEnvironment(JRE)classes. Ordering ItfollowstheLIFOorder. Itdoesnotfollowanyorderbecauseitisadynamicmemoryallocationanddoesnothaveanyfixedpatternforallocationanddeallocationofmemoryblocks. Flexibility Itisnotflexiblebecausewecannotaltertheallocatedmemory. Itisflexiblebecausewecanaltertheallocatedmemory. Efficiency Ithasfasteraccess,allocation,anddeallocation. Ithassloweraccess,allocation,anddeallocation. MemorySize Itissmallerinsize. Itislargerinsize. JavaOptionsUsed WecanincreasethestacksizebyusingtheJVMoption-Xss. Wecanincreaseordecreasetheheapmemorysizebyusingthe-Xmxand-XmsJVMoptions. VisibilityorScope Thevariablesarevisibleonlytotheownerthread. Itisvisibletoallthreads. GenerationofSpace Whenathreadiscreated,theoperatingsystemautomaticallyallocatesthestack. Tocreatetheheapspacefortheapplication,thelanguagefirstcallstheoperatingsystematruntime. Distribution Separatestackiscreatedforeachobject. Itissharedamongallthethreads. ExceptionThrows JVMthrowsthejava.lang.StackOverFlowErrorifthestacksizeisgreaterthanthelimit.Toavoidthiserror,increasethestacksize. JVMthrowsthejava.lang.OutOfMemoryErroriftheJVMisunabletocreateanewnativemethod. Allocation/Deallocation Itisdoneautomaticallybythecompiler. Itisdonemanuallybytheprogrammer. Cost Itscostisless. Itscostismoreincomparisontostack. Implementation Itsimplementationishard. Itsimplementationiseasy. Orderofallocation Memoryallocationiscontinuous. Memoryallocatedinrandomorder. Thread-Safety Itisthread-safebecauseeachthreadhasitsownstack. Itisnotthread-safe,soproperlysynchronizationofcodeisrequired. NextTopicAbstractionvsEncapsulation ←prev next→ ForVideosJoinOurYoutubeChannel:JoinNow Feedback SendyourFeedbackto[email protected] HelpOthers,PleaseShare LearnLatestTutorials Splunk SPSS Swagger Transact-SQL Tumblr ReactJS Regex ReinforcementLearning RProgramming RxJS ReactNative PythonDesignPatterns PythonPillow PythonTurtle Keras Preparation Aptitude Reasoning VerbalAbility InterviewQuestions CompanyQuestions TrendingTechnologies ArtificialIntelligence AWS Selenium CloudComputing Hadoop ReactJS DataScience Angular7 Blockchain Git MachineLearning DevOps B.Tech/MCA DBMS DataStructures DAA OperatingSystem ComputerNetwork CompilerDesign ComputerOrganization DiscreteMathematics EthicalHacking ComputerGraphics SoftwareEngineering WebTechnology CyberSecurity Automata CProgramming C++ Java .Net Python Programs ControlSystem DataMining DataWarehouse JavatpointServicesJavaTpointofferstoomanyhighqualityservices.Mailuson[email protected],togetmoreinformationaboutgivenservices.WebsiteDesigningWebsiteDevelopmentJavaDevelopmentPHPDevelopmentWordPressGraphicDesigningLogoDigitalMarketingOnPageandOffPageSEOPPCContentDevelopmentCorporateTrainingClassroomandOnlineTrainingDataEntryTrainingForCollegeCampusJavaTpointofferscollegecampustrainingonCoreJava,AdvanceJava,.Net,Android,Hadoop,PHP,WebTechnologyandPython.Pleasemailyourrequirementat[email protected]Duration:1weekto2weekLike/Subscribeusforlatestupdatesornewsletter
延伸文章資訊
- 1Java - Stack 與Heap 的分別 - iT 邦幫忙
在使用Java開發程式的過程中,相信大家都可能見過stack和heap這兩個字,例如在一些Error中、在JVM中做一些設定(heap memory space跟stack memory spa...
- 2Stack Memory and Heap Space in Java - Baeldung
Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. ...
- 3Heap vs. Stack: Code Examples, Tutorials & More - Stackify
- 4Stack vs Heap: Know the Difference - Guru99
- 5Java 面試- JVM 的Stack 和Heap - Laugh Now
JVM 記憶體的Stack 和Heap 絕對不要和其他同名的東西搞混,在這裡是做為JVM 儲存資料或指令的區域,和其他同名的東西無關,請把它當作平行宇宙看待。