开发者

GC Rules : how to findout a java object is eligible for garbage collection or not

Anyone point me the开发者_JAVA技巧 set of defined rules to find out the eligibility for garbage collection of java objects and a simple example for that .


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:

  • A has a reference to O, or
  • A has a reference to an object from which O is reachable

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜