LARA

Idea of Garbage Collection

Idea:

  • 'free' violates memory-safety and type-safety
  • instead, let the run-time system automatically free memory that is guaranteed not to be used any more
  • memory that will not be used is called garbage
  • algorithms that reclaim such memory are garbage collectors

How do we know what is garbage?

  • cannot know precisely
  • but unreachable objects are surely garbage
  • garbage collection therefore collects unreachable objects and free-s them
  • invoked periodically or when need to free up memory

Example:

  class Node {
    var next : Node = null
    var data : Int = 0
  }
  def main(args : Array[String]) = {
    var x : Node = new Node()
    var y : Node = new Node()
    x.next = y
    x.data = 42
    var z : Node = x.next
    x = null
    y = null
    // GC invoked here
    z.data = 9
  }