Professional Documents
Culture Documents
Garbage Collection
Garbage Collection
1
A Fundamental tradeoff
2
Basic tradeoffs by different strategies
Manual deterministic
Ref counting
CPU Mark/Compact
heuristic
Mark / Sweep
Copy collect
RAM
3
GC and the CLR
4
CLR heap usage
a b a.b a2 b a2.b
A func()
{ Start of free space
A a = new A();
a.b = new B();
A a2 = new A();
a2.b = new B();
return a2;
}
5
GC
6
Phase I: Mark
7
Marking objects
cycles are
not a problem
8
Phase II: Compact
9
After Compaction
Live objects
Free space
Root set
10
A real life example
memory usage
12
Finalizers and compaction
freachable queue
Live objects
Pending Finalize
Free space
Root set
13
Memory cost of finalizers
Finalizers
no Finalizers
14
Controlling Finalization
15
Example: IDisposable and SuppressFinalize
public class Transaction : IDisposable {
public Transaction() {
lowLevelTX = raw.BeginTransaction();
}
17
Generations, cont’d
18
Generations, cont’d
19
The Large Object heap
20
Large object heap behavior
address
22
Thread hijacking
int bar()
{
return 5;
}
GC
int foo()
{
int ret =bar();
return ret;
}
23
Safe Points
• For longer methods Jitter will add callouts to code to check for a
GC
– Callouts are made at places deemed safe for GC to occur
• If runtime is beginning a GC cycle then method will halt at safe
point until GC is completed
24
Fully Interruptible code
25
Arenas
26
Arenas: Single CPU
Thread 1
Thread 2
Thread 1
Thread 2
• GC involves tradeoffs
• Techniques chosen by MS give reasonable performance for a
wide variety of languages / patterns
• GC is mostly automatic
– But can be influenced via System.GC class
• Try to minimize use of Finalizers
– Saves CPU and memory
• Details certain to change in future
– As MS tweaks implementation
29