Reputation: 26364
Anyone point me the set of defined rules to find out the eligibility for garbage collection of java objects and a simple example for that .
Upvotes: 2
Views: 2072
Reputation: 10445
Objects are eligible for GC'ing once they're no longer reachable from any thread.
An object O is reachable from another object A if either:
So if you had: class Foo { Bar x = new Bar(); }
and class Bar { Bar y = new Baz(); }
,
and one of your threads had an instance of Foo
, then the instances of Foo
, Bar
and Baz
would all be reachable and not eligible for GC. (The thread has a reference to the Foo
instance, which has a reference to the Bar
instance, which has a reference to the Baz
instance).
If you then set x
to null
(or another object) in your instance of Foo
, neither the Bar
or Baz
instances would be reachable any more. (The thread has a reference to the Foo
instance still, and the Bar
instance has a reference to the Baz
instance, but the Foo
instance no longer holds a reference to the Bar
instance). Both the Bar
and Baz
instances would therefore both be eligible for GC.
Upvotes: 4