View
215
Download
1
Embed Size (px)
Citation preview
Implications of Implications of Substitution Substitution
Fall 2005 OOPDFall 2005 OOPDJohn AnthonyJohn Anthony
TopicsTopics
Memory Allocation StrategiesMemory Allocation Strategies The Java Memory Allocation ModelThe Java Memory Allocation Model A Java Stack and Heap ExampleA Java Stack and Heap Example Memory Allocation and InheritanceMemory Allocation and Inheritance An Example in C++ Using the StackAn Example in C++ Using the Stack Reference Assignment StrategiesReference Assignment Strategies
Memory AllocationMemory Allocation
Generally broken down into two Generally broken down into two strategies (although variance does strategies (although variance does exist).exist).
Static (Stack-based) Static (Stack-based) AllocationAllocation
Static allocationStatic allocation means means allocationallocation of of memory before the program starts and memory before the program starts and retention until the end.retention until the end.
Compiler determines the exact size of the Compiler determines the exact size of the data structure based on the software text.data structure based on the software text.
Memory allocation and release is Memory allocation and release is determined at procedure entry and exit.determined at procedure entry and exit.
This means that the size of the program and This means that the size of the program and its “data” are determined before execution.its “data” are determined before execution.
Dynamic (Heap-based) Dynamic (Heap-based) AllocationAllocation
Dynamic allocationDynamic allocation means means allocationallocation of of memory during program execution.memory during program execution.
Compiler cannot determine the exact size of Compiler cannot determine the exact size of the data structure based on the software the data structure based on the software text.text.
Memory allocation and release is Memory allocation and release is not not determined at procedure entry and exit.determined at procedure entry and exit.
Memory release either handled by Memory release either handled by programmer or system (garbage collection).programmer or system (garbage collection).
Java (Thread) Execution Java (Thread) Execution StateState
Execution state of a Java thread has several runtime data areas:
Java stacksuccession of frames representing method calls
Object heapObjects used by a thread
Method areaClasses used by a thread
The Java StackThe Java Stack
A new frame for each A new frame for each method executionmethod execution
A frame includes A frame includes local variables of the local variables of the associated method associated method and operand stack and operand stack that contains partial that contains partial results (operands)results (operands)
A frame also contains A frame also contains registers such as the registers such as the program counterprogram counter
Stack, Heap, and Method Stack, Heap, and Method AreaArea
The heap associated with a thread contains all the The heap associated with a thread contains all the objects used by the thread (objects accessible objects used by the thread (objects accessible from the thread’s Java stack)from the thread’s Java stack)
The Class Pool associated with a thread contains The Class Pool associated with a thread contains the classes used by the thread.the classes used by the thread.
Class Pool Stack Object heap
Class Referen
ce Object Referen
ce
Stack – A Closer LookStack – A Closer LookJava Code Java Code StackStack
> int x;> int x;
> x = 5;> x = 5;
> double min = 0.5;> double min = 0.5;
> boolean done = false;> boolean done = false;
Fernando Pereira University of Pennsylvania
Stack & Heap – A Closer Stack & Heap – A Closer LookLook
Java CodeJava Code Stack and HeapStack and Heap> int x = 99;> int x = 99;
> Counter c1;> Counter c1;
> c1> c1
nullnull
> c1 = new Counter();> c1 = new Counter();
> c1> c1
Counter@2f996fCounter@2f996f
> c1.incrementCount();> c1.incrementCount();
> Counter c2 = new Counter();> Counter c2 = new Counter();
> c2> c2
Counter@4a0ac5Counter@4a0ac5
Fernando Pereira University of Pennsylvania
Value of a Reference Value of a Reference VariableVariable
The value of are reference variable is either null The value of are reference variable is either null or a “heap address” or a “heap address”
Example:Example: > Counter c1;> Counter c1; > c1> c1 nullnull > c1 = new Counter();> c1 = new Counter(); > c1> c1 Counter@e05ad6Counter@e05ad6
e05ad6 is a hexadecimal (base 16) numbere05ad6 is a hexadecimal (base 16) number We don’t have to (and can’t) deal with these hex We don’t have to (and can’t) deal with these hex
numbers directlynumbers directly
Fernando Pereira University of Pennsylvania
““Has a” RelationshipHas a” Relationship We’ll look at an example where an object A has an instance We’ll look at an example where an object A has an instance
variable which is an object whose type is B. (A “has a” B.) variable which is an object whose type is B. (A “has a” B.) We will create a DormRoom object, and a Freshman object We will create a DormRoom object, and a Freshman object
whose room is that DormRoomwhose room is that DormRoom
What code should we write?
What will the stack and the heap will look like?
public class DormRoom{ private int num; private String bldgName; public DormRoom(int n, String b){ num = n; bldgName = b; } public String getLocation(){ return num + " " + bldgName; }}
> DormRoom room = new DormRoom(208, "Hill");> DormRoom room = new DormRoom(208, "Hill");
> room.getLocation()> room.getLocation()
"208 Hill""208 Hill"
DormRoom Code and UMLDormRoom Code and UML
A DormRoom on the HeapA DormRoom on the Heap
> DormRoom room = new DormRoom(208, "Hill");> DormRoom room = new DormRoom(208, "Hill");
> room.getLocation()> room.getLocation()
"208 Hill""208 Hill"
public class Freshman{ private String name; private DormRoom room; public Freshman(String n, DormRoom r){ name = n; room = r; } public String getName(){ return name;} public DormRoom getRoom(){ return room;}}
> DormRoom room = new DormRoom(208, "Hill");> DormRoom room = new DormRoom(208, "Hill");
> Freshman f = new Freshman("jo", room);> Freshman f = new Freshman("jo", room);
> f.getName()> f.getName()
"jo""jo"
> f.getRoom().getLocation()> f.getRoom().getLocation()
"208 Hill""208 Hill"
Freshman Code and UMLFreshman Code and UML
A Freshman on the A Freshman on the Heap :)Heap :)
> DormRoom room = new DormRoom(208, "Hill");> DormRoom room = new DormRoom(208, "Hill");
> Freshman f = new Freshman("jo", room);> Freshman f = new Freshman("jo", room);
> f.getName()> f.getName()
"jo""jo"
> f.getRoom().getLocation()> f.getRoom().getLocation()
"208 Hill""208 Hill"
Memory Allocation and Memory Allocation and InheritanceInheritance
If Stack Allocation is a more efficient If Stack Allocation is a more efficient memory allocation and reclamation memory allocation and reclamation strategy, then why use the heap?strategy, then why use the heap?
Let’s look at one challenge as seen Let’s look at one challenge as seen through the eyes of C++ and through the eyes of C++ and polymorphism.polymorphism.
Consider the following….Consider the following….class Window {class Window {
public:public:
virtual void oops();virtual void oops();
private:private:
int height;int height;
int width;int width;
};};
class TextWindow : public Window {class TextWindow : public Window {public:public:
virtual void oops();virtual void oops();private:private:
char * contents;char * contents;int cursorLocation;int cursorLocation;
};};
If we create a new Window (Window win;), how much space on the Stack should be allocated?
Three ChoicesThree Choices
Allocate enough memory for the base Allocate enough memory for the base class only. (C++)class only. (C++)
Allocate the maximum memory Allocate the maximum memory needed for any legal value (base or needed for any legal value (base or subclass).subclass).
Allocate enough space to only hold a Allocate enough space to only hold a pointer. (Smalltalk, Java)pointer. (Smalltalk, Java)
Minimum Static Space Minimum Static Space AllocationAllocation
C++ uses this approach.C++ uses this approach. What happens when we execute the What happens when we execute the
following code:following code:
Window win;Window win;Window *tWinPtr;Window *tWinPtr;......tWinPtr = new TextWindowtWinPtr = new TextWindow......Win = *tWinPtrWin = *tWinPtr
SlicingSlicing
height
width
…
height
width
…
contents
cursorLocation
…
void Window::oops() {void Window::oops() {
cout << “Window oops”” << endl;cout << “Window oops”” << endl;
}}
Void Window::oops() {Void Window::oops() {
cout << “TextWindow oops”” << cursorLocation << endl;cout << “TextWindow oops”” << cursorLocation << endl;
}}
Rules for Member Function Rules for Member Function Binding in C++Binding in C++
Variables declared as references or pointers, Variables declared as references or pointers, the binding of the function name to the the binding of the function name to the function body is based on the dynamic class function body is based on the dynamic class (as you’d perhaps expect).(as you’d perhaps expect).
With variables that are not pointers (i.e. With variables that are not pointers (i.e. declared on the stack), the binding of the declared on the stack), the binding of the function name to the function body is based on function name to the function body is based on the static class.the static class.
ExampleExample
Window win;Window win;
TextWindow *tWinPtr, *tWin;TextWindow *tWinPtr, *tWin;
..
..
..
tWinPtr= new Textwindow;tWinPtr= new Textwindow;
win = * tWinPtr;win = * tWinPtr;
tWin = tWinPtr;tWin = tWinPtr;
Win.oops();Win.oops();
tWin.oops();tWin.oops();
Maximum Static space Maximum Static space AllocationAllocation
Eliminates slicing problem by allocating the Eliminates slicing problem by allocating the maximum amount of memory necessary.maximum amount of memory necessary.
In order to do this, the entire program In order to do this, the entire program needs to be scanned.needs to be scanned.
What about dynamic class loading….?What about dynamic class loading….?
No major OO language takes this approach No major OO language takes this approach due to restriction of “program scan”.due to restriction of “program scan”.
Dynamic Memory Dynamic Memory AllocationAllocation
The value is stored in a separate data area called The value is stored in a separate data area called the Heap.the Heap.
Fixed size pointers are stored on the Stack and Fixed size pointers are stored on the Stack and point to the heap.point to the heap.
Space on the heap is allocated when the object is Space on the heap is allocated when the object is created via the “new” keyword (for Java).created via the “new” keyword (for Java).
What happens when after executing an What happens when after executing an assignment statement?assignment statement?
Pointer AssignmentPointer AssignmentCounter c1 = new Counter();Counter c1 = new Counter();
Counter c2 = new Counter();Counter c2 = new Counter();
c2 = c1;c2 = c1;
c1
c2
0
0
Stack Heap
Counter
Counter
Copy AssignmentCopy AssignmentCounter c1 = new Counter();Counter c1 = new Counter();
Counter c2 = new Counter();Counter c2 = new Counter();
c2 = c1;c2 = c1;
c1
c2
0
0
Stack Heap
Counter
Counter
0 Counter
Copied as a result of
assignment
A Hybrid ApproachA Hybrid Approach
c1
c2
0
0
Stack Heap
Counter
Counter
0 CounterCopied as a
result of modification
(not assignment)
Counter c1 = new Counter();Counter c1 = new Counter();
Counter c2 = new Counter();Counter c2 = new Counter();
c2 = c1;c2 = c1;