Wednesday 14 August 2013

Heap, Stack and CLR (st)

MEMORY MANAGEMENT: VALUE v/s REFERENCE TYPES

• OS and runtimes often divide the memory used for holding the data into two separate chunks, each of which is managed in a distinct manner
• The two chunks of memory are traditionally called stack and heap
• The Stack and Heap serve different purposes:
o When a method is called, the memory required for its parameters and its local variables is always acquired from the stack
o When the method finishes (return value/throw exception), the memory acquired for the parameters and local variables is automatically released back to the stack and is available for reuse when another method is called
o When an object is created using the new keyword and a constructor call, the memory required to build the object is always acquired from the heap
o Same object can be referenced from several places by using reference variables. When the last reference to an object disappears, the memory used by the object disappears, the memory used by the object becomes available for reuse

CONECEPTS OF STACK AND HEAP
• Stack memory is organized like a stack of boxes piled on top of each other
• When a method is called, each parameter is put in a box, which is placed on top of the stack
• Each local variable likewise is assigned a box, and these are placed on top of the boxes already on the stack
• When a method finishes, all its boxes are removed from the stack
• Heap memory is like a large pile of boxes strewn around a room rather than stacked neatly on top of each other
• Each box has a label indicating whether it is in use or not
• When a new object is created, the runtime searches for an empty box and allocates it to the object
• The reference to the object is is stored in a local variable on the stack.
• The runtime keeps a track of the number of references to each box (important to remember that two variables can refer to the same object)
• When the last reference disappears, the runtime marks the box as not in use, and at some point in the future will empty the box and make it available for reuse
• IMPORTANT: Although the object itself is stored on the heap, the reference to the object is stored on the stack
• Heap memory is NOT infinite. If heap memory is exhausted, the new operator will throw OutOfMemoryException and the object will not be created