Wednesday, May 26, 2010

How does Java allocate stack and heap memory? Explain re-entrant, recursive and idempotent.

Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like
int and double 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. This is why care should be taken in your code to avoid any
concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the
heap is not threadsafe unless guarded with synchronisation through your code.


A method in stack is reentrant allowing multiple concurrent invocations that do not interfere with each other. A
function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java
though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms. All
recursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods,
which are written in such a way that repeated calls to the same method with the same arguments yield same
results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a
server failure as long as it can reach another server.

(from http://javapeople.blogspot.com/2007/02/how-does-java-allocate-stack-and-heap.html)