0
votes

I know the CMS garbage collector uses the mark sweep algorithm,I am curious about how it marks the object.

CMS initial mark: why does it mark the reachable objects rather than mark unreachable objects?

1
JVM does not mark unreachable objects because... it obviously cannot reach them :) I mean, by walking through the graph of references. In order to find unreachable objects, JVM needs to iterate over the whole heap and exclude live objects. - apangin

1 Answers

2
votes

The garbage collector's task is to find objects that your program can no longer reach by following whatever chain of accessor steps, and to reclaim the memory occupied by them.

The Mark-Sweep GC does that the other way round: it first finds all objects that can still be reached, and then reclaim the memory of all the other objects.

Simplified Mark-Sweep algorithm (of course the real one is far more complex):

  • Start with all directly-reachable references, e.g. local variables on the stack (arguments and locals from all not-yet-finished method calls), static fields etc.
  • Mark the objects they point to.
  • Recursively inspect the newly-marked objects. Mark the objects referenced by their fields.
  • Repeat until you get no more new marks.
  • Loop over your memory object-by-object and reclaim the memory of every object without a mark.
  • Finally remove all marks.