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

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 re-entrant 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.


6 comments:

  1. Excellent explanation thanks!

    ReplyDelete
  2. Thanks Buddy,Nice Explanation.........

    ReplyDelete
  3. Sant Ritz's charming address offers a world of opportunities for your little ones in the future.the interlace condo :: theinterlacecondo.sg ::

    ReplyDelete
  4. can there will be an object without class and vice versa???

    ReplyDelete
  5. 7a replica bags wholesale these details q2r11g0d98 replica bags near me check over here e7y63o6s82 replica designer bags replica bags reddit useful site q2l82f3a59 replica bags china replica bags wholesale d5p84p4a92

    ReplyDelete