Thursday, 8 October 2015

How does Java allocate stack and heap memory?

How does Java allocate stack and heap memory?

Object is always allocated in memory known as heap. If object is created in method (local) will also allocated in heap, but the pointing variable will be in stack.

Primitive variables are allocated in the stack (if they are local method variables) and in the heap (if they are member variables i.e. fields of a class).

In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.

In a multi-threaded application each thread will have its own stack but will share the same heap.

The stack is thread safe (each thread will have its own stack) but the heap is not thread safe unless guarded with synchronization through your code.

1 comment:

Related Posts Plugin for WordPress, Blogger...