Wednesday 29 July 2015

Java Source World: Java stack and heap

Java stack and heap | Java Source World

Java Source World A Java quick reference blog


Java Memory 



Java Memory is one of the most interesting concepts in JVM and its always fun to know how java memory model is designed. Java memory model (JMM) has quite a few components of which stack and heap are two of them.



  • JVM has some space allocated to heap and stack. JVM stack stores local variables, method pointers and function call whereas heap is used to store class level variables, java class objects, string pool.
  • JVM has a heap that is shared across all Java threads. Each java thread has its own stack called as stack frames, where it stores local variables and stack pointers .
  • If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space
  • If you are using recursion, on which method calls itself, you can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is lot lesser than size of heap memory in Java.
  • JVM heap is configurable using -Xmx and -Xms and stack size can be configured using -Xss
  • The lifetime of stack is the longetivity of thread, where as heap is present as long application is running. Garbage collections runs on heap.
  • Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it.

Java Source World A Java quick reference blog

No comments:

Post a Comment