Professional Documents
Culture Documents
Garbage Collection: Object Oriented Paradigm
Garbage Collection: Object Oriented Paradigm
Garbage Collection
Major Areas of Memory
• Static area
− Fixed size, fixed content, allocated at compile time
• Run-time stack
− Variable size, variable content (activation records)
− Used for managing function calls and returns
• Heap
− Fixed size, variable content
− Dynamically allocated objects and data structures
− Examples: ML reference cells, malloc in C, new in Java
2
Object De-allocation
• How are objects deallocated?
• Storage classes:
static - never deallocated, same lifetime as the program
stack - deallocated automatically on subroutine return
heap - explicit or implicit deallocation
• Implicit deallocation
− Garbage collection
3
Garbage
4
Dangling References
5
Example of Garbage
class node {
int value; p = new node();
node next; q = new node();
} q = p;
node p, q; delete p;
6
Dangling References
• Dangling references can only be produced in languages
with explicit deallocation.
− Programmer may deallocate an object that is still referred by live
pointers
− Garbage collection will check if an object still has references to it
before deleting it
7
Tombstones
8
Tombstones
• Tombstones are special heap cells that represent
proxies for allocated heap cells.
9
Tombstones
10
Lock-and-key
11
Lock-and-key
12
Lock-and-key
13
Garbage Collection
• Garbage collection
− Essential for functional languages - frequent construction and return
of objects from functions
− Mechanisms:
− Reference Counter
− Mark-and-Sweep
14
Reference Counter
• How do we know when a heap object is no longer useful?
− when there are no pointers to it
• Solution
− in each object keep a reference counter = the number of pointers
referring the object
− when allocating the object:
int r; Student p;
st = new Student();
Heap space
root
set 1
1 1 1
1 2 1
16
Reference Counts
• Problem - circular lists:
• The objects in the list are not reachable, but their reference
counts are non-zero
17
Reference Counter
18
Mark-and-Sweep Collection
19
Mark-Sweep Example
Heap space
root
set
slide 20
Mark-Sweep Example
Heap space
root
set
slide 21
Mark-Sweep Example
Heap space
root
set
slide 22
Mark-Sweep Example
Heap space
Free unmarked
root cells
set
slide 23
GC and Programming Languages
• Recent GC revival
− Object-oriented languages: Modula-3, Java
− In Java, runs as a low-priority thread; System.gc may be called
by the program
− Functional languages: ML and Haskell
24