Java Garbage Collection – Which Memory Part is Used?

garbage-collectionjava

I understand the Heap memory divisions such as Young, tenured and Perm Gen.
But I'm just curious from where is the memory used for performing the Garbage Collector itself? Is it from any of these memory spaces or in the thread stacks ?

Best Answer

The answer depends on what you mean by "the memory used for performing the Garbage Collect[ion]" ... and what garbage collector you are talking about.

The general answer is that different garbage collection algorithms use space differently. This is a very high level / simplified summary:

  • Just about all garbage collectors make use of one or more "mark" bits in each object's header to record that the object has been processed by the GC.

  • Copying collectors work by copying live objects from a "from" space to a "to" space, and in the simple case don't need any extra space.

  • Mark / sweep collectors work by recursively walking the graph of "reachable" objects. The recursion can be done explicitly (which requires a separate stack), or by means of a clever pointer-reversal trick (look up Cheney's algorithm).

  • Concurrent collectors typically require extra memory to track objects that get mutated while the garbage collector is running.

There are whole books on the topic of garbage collection. If you want to really understand how garbage collectors work under the hood, you've got a lot of reading to do.


In general, any additional memory that the GC needs to do its job will typically be allocated outside of the live heap spaces. Thread stack memory is not used ... apart from the thread stack for the garbage collection thread or threads themselves.

Your mention of "young", "tenured" and "permgen" suggests that you are talking about classical Java GCs. These are generational collectors, which is a subtype of copying collectors.