Stack Vs Heap Java - Javatpoint

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

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



請為這篇文章評分?