Monday, 24 February 2014

Java Stack and Heap

Stack:


In JVM each thread has a private stack created at the same time when a thread is created. It holds all the local variables and its results. When a main method is called main thread will be created by default and it will be always on the bottom of the stack. The methods invoked from main will be added further on the stack.
Package thread;
/**
* @author Sivaranjani D
*
*/
public class FirstThread  {
public static void main(String args[])throws Exception{
System.out.println("Current Thread :"+Thread.currentThread().getName());
}
}

Output:
Current Thread :main

But when a new thread is created, the method invocations by the thread will be started in a new stack. The execution of main thread and the newly created threads happen in parallel.when run method completes stack will be closed for that stack.

Thread Stack explained:

 

[caption id="attachment_433" align="alignnone" width="770"]java stack java stack[/caption]

Here concurrent means, whenever JVM gets a chance to execute inside a CPU (Single core systems), it acts as a mini-OS and schedule its threads internally.

The JVM specifications of different vendors permits either fixed sized stack or dynamically extendable/contractible stacks depends on their implementations.

Exceptions:

StackOverfloError, if a computation in a thread requires more than the permitted stack size.

HEAP:

JVM has a heap that is shared among all the instance and threads. It will be created on JVM start-up. Heap size can be extended or contracted based on the JVM specification. Once the computation is over the no longer used instances will be garbage collected.

Heap size can be increased with the JVM options -Xms and -Xmx.  Xms denotes starting size of Heap while -Xmx denotes maximum size of Heap in Java.

Exceptions:

When the computation requires more memory than allocated, OutOfMemory error is shown.

No comments:

Post a Comment