Garbage collector

Automatic memory release: object reachable from the roots, reclaimable object, mark and sweep, reference counting and cycles, leaks through a reference kept by accident.

  • 29 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. The steps
  5. Scenarios

A few cards from the deck

  • Garbage collector: what is it?

    Show the answer

    The runtime mechanism that automatically frees the memory of objects the program can no longer use.

    In Java and Python, you write no free. The timing of a pass is up to the virtual machine: System.gc() is only a suggestion, with no guarantee.

  • After this code, which objects are reclaimable?

    ```java
    Noeud a = new Noeud("A");
    Noeud b = new Noeud("B");
    Noeud c = new Noeud("C");
    a = b;
    c = null;
    `

    • Objects A and C
    • Object C only, since A is still referred to
    • Object A only, since C was set to null
    • Objects B and C, since B was copied
    Show the answer

    Objects A and C

    After a = b, variables a and b both refer to object B, and nothing refers to object A any more. c = null cuts the only reference to object C. B stays reachable.

  • An object is … when no path of references links it to a … any more.

    Show the answer

    An object is reclaimable when no path of references links it to a root any more.

    That is the only criterion: it does not matter whether the object still has references to other objects, or whether it is referred to by an object that is itself unreachable.

  • Root: what is it?

    Show the answer

    A starting point of the program where a reference is directly usable: local variables of the running methods, static attributes.

    Everything you can reach by following references from a root is alive. An object no root can reach is unusable.

  • One mark-and-sweep pass: which step comes after "Find the program's roots"?

    • Mark the objects the roots refer to
    • Follow the marked objects' references and mark what they reach
    • Go through the heap looking for unmarked objects
    • Free the unmarked objects
    Show the answer

    Mark the objects the roots refer to

    Sweeping can only begin once marking is finished: while references remain to follow, an unmarked object might still be alive.