Garbage Collection records not reachable reclaim to allow reuse performed by runtime system (support programs linked with the compiled code) (support programs linked with the compiled code)
Record Types live – will be used in the future not live – will not be used in the future reachable – able to be accessed via programs
Types of Algorithms Mark-And-Sweep Collection Reference Counts Copying Collection Generational Collection Incremental Collection Baker’s Algorithm
Mark-And-Sweep Collection Program variables and heap records form a directed graph Roots are the variables node n is reachable if r -> … -> n r -> … -> n Depth first search marks reachable nodes Any node not marked is garbage
Cost of Garbage Collection Depth first search takes time proportional to the number of reachable nodes Sweep phase takes time proportional to the size of the heap
Maintaining Free Space Create a list of free space Search for a space of size N might be long Maintain several free lists of differing sizes External fragmentation a problem Internal fragmentation can also be a problem
Reference Counts Count the number of pointers point to each record Store the reference count with each record If p addresses an alternate record, decrement the old and increment the new If count reaches 0, free record
When to Decrement Instead of decrementing the counts a record references when the record is placed on the free list, it is better to do this when the record is removed from the free list. Instead of decrementing the counts a record references when the record is placed on the free list, it is better to do this when the record is removed from the free list.
Why Breaks the recursive decrementing work into shorter pieces Compiler emits code to check whether the count has reached 0, but the recursive decrementing will be done only in one place, in the allocator
Problems with Reference Count Cycles of garbage cannot be reclaimed Incrementing the reference counts is very expensive
Solutions-Cycles, Expensive Require the programmer to break the cycle Combine reference counting with mark-sweep No solution for it being expensive Problems outweigh advantages, thus rarely used
Copying Collection Reachable part is a directed graph with records as nodes, pointers as edges, and variables as roots Copy the graph from “from-space” to “to-space” Delete all “from-space”qq