Popular Posts

Friday, December 16, 2011

Difference Between Stack and Heap Memory and/or StackOverflowError and OutOfMemoryError.

What Is Heap?
The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the runtime data area from which memory for all class instances and arrays is allocated. 
The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly de-allocated.
The heap mainly store objects create using or class level variables.

The following exceptional condition is associated with the heap: 
  • If a computation requires more heap than can be made available by the automatic storage management system, the Java virtual machine throws an OutOfMemoryError.

What Is Stack?
Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread. A Java virtual machine stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Because the Java virtual machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated. The memory for a Java virtual machine stack does not need to be contiguous.

The Java virtual machine specification permits Java virtual machine stacks either to be of a fixed size or to dynamically expand and contract as required by the computation
The following exceptional conditions are associated with Java virtual machine stacks:
  • If the computation in a thread requires a larger Java virtual machine stack than is permitted, the Java virtual machine throws a StackOverflowError
  • If Java virtual machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java virtual machine stack for a new thread, the Java virtual machine throws an OutOfMemoryError.

ONLY Local variables (including method parameters) go on the STACK.
Everything else goes on the HEAP. As variables don't store objects; they only hold primitives and references - so all objects go on the heap. And all class definitions go on the heap (in method area).
String pool is also stored in Permanent generation (or Perm Area) of heap.
Also see..

No comments: