Thursday, August 11, 2011

Threads and Stacks

Whenever a java program starts, the compiler sets-up a stack frame on the run-time stack, pushes arguments and calls the function.  The stack is also used as temporary storage for locally allocated objects declared in the scope of a procedure.

In a sequential program, there is only one run-time stack and all function calls, arguments, local variables/objects are allocated in a nested fashion on the same run-time stack,

In a multithreaded application, each “thread” gets a separate run-time stack.

In a sequential program, the main run-time stack is allocated at program start and all procedure
calls, including the initial call to “main” are made on this single run-time stack.  If the main procedure creates a new thread, then a new run-time stack is dynamically allocated from the heap and all function calls, arguments, local variables/objects from the run method of the thread are allocated on this new stack. The first element on any thread's stack is the run() method.

So, the thread stack needs to be large enough to hold the maximum number of bytes required to hold all  function calls, arguments, local variables/objects allocated on the stack. Generally in Operating systems stack allocation is typically set at 1MB, consisting of contiguous virtual memory pages, that are allocated incrementally at run-time by the system

In a stack, extra memory pages allocated “above” the top and “below” the bottom of the stack to detect overflow OR underflow (underflow stack frame raises exception if empty stack is “popped” - overflow raises exception when Stack is full and still items are being pushed).


No comments:

Post a Comment