What are the roots in garbage collection?
I have read the definition of root as "any reference that you program can access to" and definition of live is that an object that is being used, which can be a local variable, static variable.
I m little confused with discriminating the difference between root and live objects.
What is path to root? How does root and live objects work?
Can someone elaborate ?
 
                        
If you think of the objects in memory as a tree, the "roots" would be the root nodes - every object immediately accessible by your program.
There are four objects; a person, a red car, its engine and horn. Draw the reference graph:
And you'll end up with
Personat the "root" of the tree. It's live because it's referenced by a local variable,p, which the program might use at any time to refer to thePersonobject. This also goes for the other objects, throughp.car,p.car.engine, etc.Since
Personand all other objects recursively connected to it are live, there would be trouble if the GC collected them.Consider, however, if the following is run after a while:
And redraw the graph:
Now the
Personis accessible throughpand the blue car throughp.car, but there is no way the red car or its parts can ever be accessed again - they are not connected to a live root. They can be safely collected.So it's really a matter of taking every starting point (every local variable, globals, statics, everything in other threads and stack frames) — every root — and recursively following all the references to make up a list of all the "live" objects: objects which are in use and unsuitable for deletion. Everything else is garbage, waiting to be collected.