Friday, 22 April 2016

How does Java allocate stack and heap memory ?


Each time an object is created in Java it goes into the area of memory known as heap.
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 threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronization through your code.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.