In computer science, a root set is a set of pointers that serve as starting points for the garbage collector to find all live objects in memory. In other words, the root set contains all the objects that are directly or indirectly reachable from the program’s execution stack or from registers.
During garbage collection, the garbage collector starts with the root set and traces all objects that are reachable from the root set. Any objects that are not reachable from the root set are considered garbage and can be safely reclaimed by the garbage collector.
In Java, the root set typically includes the following:
Local variables in the program’s execution stack
Static fields in the program’s classes
Objects referenced by the current thread’s call stack
JNI (Java Native Interface) global references
System classloader and bootstrap classloader
JVM internal data structures
The root set is critical for the garbage collector’s ability to correctly identify all live objects in memory. If any live objects are not reachable from the root set, they will not be traced and will be incorrectly treated as garbage.
One important consideration for developers is to ensure that any objects that are intentionally kept alive (such as caches or global variables) are included in the root set. This can be accomplished by holding a reference to these objects in one of the root set components (such as a static field or JNI global reference).