In this tutorial, we’ll learn what the Garbage Collector Roots (GC roots) are. Additionally, we’ll describe the types of GC roots. Afterward, we’ll show the difference between GC roots and live objects.
2. GC Root Definition
Let’s first define what GC roots are. GC root is a term used in the context of garbage collection in Java. They are special objects for the garbage collector. As the name suggests, GC roots are starting points for the garbage collector processes. In general, all objects directly or indirectly referenced from a GC root are not garbage collected.
3. Types of GC Roots
Let’s have a look at the main types of GC Roots:
- Class: Classes loaded by a system class loader; contains references to static variables as well
- Stack Local: Local variables and parameters to methods stored on the local stack
- Active Java Threads: All active Java threads
- JNI References: Native code Java objects created for JNI calls; contains local variables, parameters to JNI methods, and global JNI references
Additionally, there are a few more possible types of GC Roots:
- Objects used as monitors for synchronization
- Specific objects defined by the JVM implementation that are not garbage collected for its purpose. That might contain important exception classes, system class loaders, or custom class loaders
Furthermore, there is no documentation per JVM about which specific objects are GC roots. Some of the popular Java IDEs provide the functionality to analyze memory from the GC roots perspective. This is beneficial when analyzing memory leaks in an application.
4. GC Roots vs. Live Objects
Let’s now have a look at the live objects defined in the garbage collection process.
All objects actively used by an application are live objects for GC. Furthermore, the garbage collector doesn’t delete live objects. GC roots are a special type of live object. Therefore, all GC roots are live objects by definition.
5. Garbage Collector Usage of GC Roots
Let’s now have a look at the usage of GC Roots in the garbage collection process.
As a matter of fact, all GC implementations in the HotSpot JVM are tracing collectors. GC identifies all live objects by traversing the objects graph. In addition, objects visited and marked as alive won’t be garbage collected. To be able to traverse the graph, starting points are necessary. Thus, GC roots are starting points for tracing collectors.
GC starts traversing the graph from the root and marks all visited objects in the graph as alive. The process executes for every GC root defined in an application. Moreover, it processes all graphs starting from all GC roots. Then, it marks all visited objects as alive. After that, all objects that haven’t been visited are garbage collected.
In this short article, we explained what GC roots are. Then, we described the types of GC roots. Next, we showed the difference between GC roots and live objects. Finally, we explained the usage of GC roots in the garbage collection process.