What is GC root in JAVA
The fundamental to the Garbage Collection is NOT to get rid of dead objects by identifying them, but by traversing the live object graph and garbage collect all but these live objects. This process of traversing the live object graph start from source of all object tree, called GC root.
Why GC root matters
Heap is an area of dynamic memory allocation. JVM borrows memory from Operating System at once, based on configured settings. Hence JVM don't have to bother OS each time a new object needs to be added into memory making it faster object creation by eliminating global OS synchronization overhead. Now, when object is removed from memory, JVM doesn't give back this memory space to OS, but keep it for any future object creation. So, in short, JVM manages memory. Question is, when many objects refer to many objects, what helps JVM determine which objects are no longer needed, like where to start as very first starting point in this search? here comes GC root.
GC start traversing all object from GC root, and mark all objects as live linked in this graph.
Types of GC roots
- Local Variables : These are stack thread managed, and covers local variables, method arguments stored and kept alive by stack thread.
- Static Variables : As these are referenced by classes, a removal of classes will remove these variables as well, so they can be consider as GC root
- Active Threads : These covers all active threads in JVM, threads by definition are active objects
- *Monitors *: To achieve true operation synchronization monitors are used, like wait(), notify() in java, these guarantee only one process will execute code inside monitors
- Special Objects : Example of these are exception classes, classes loaded by system classloader, which will never be unloaded or custom classloaders.
- *JNI Reference *: java objects as a result of native calls, includes local variables, parameters to JNI methods etc
Top comments (0)