permaculture playing cards
The moose likes Beginning Java and the fly likes circular object reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "circular object reference" Watch "circular object reference" New topic

circular object reference

mrudul joshi
Ranch Hand

Joined: Nov 12, 2003
Posts: 54
could you please explain circular object reference in relation to garbage collection in detail?
if obj1 can be referenced from obj2 and obj2 can be referenced from obj1, will they both be ellibible for garbage collection ?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

There are many ways a garbage collector might work. One way is by "reference counting". Every object would contain a count of how many pointers pointed to it; the collector woiuld discard objects with a 0 count. This is simple to implement, but it has obvious problems: every object has to contain a count, which wastes space; plus cycles would prevent the collector from working, as you seem to have guessed; also, pointer assignment becoems more expensive because the count has to be updated. Reference counting isn't used in any JVM that I'm aware of.
The other broad class of GC algorithms are called "mark and sweep" algorithms. Basically, the collector goes through all of memory, "marking" those objects that can be referenced from a root object or objects. Then it makes another pass through, deleting the unmarked objects. Isolated cycles never get marked, so they're deleted nicely.
There are many different ways to improved the basic mark-and-sweep algorithm; especially, you can divide the heap into "generations" depending on object age. Older objects tend to be collected less, newer ones more, and so you can save lots of time by not looking at the older generations very often.
Most, if not all, JVMs use some kind of generational mark-and-sweep collector.

[Jess in Action][AskingGoodQuestions]
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Circular object reference is the case where two objects have reference to each other. If neither object can be referenced from the base reference or some object the can be referenced on the base reference chain then they will be swept out by the algorithm Ernest described.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
mrudul joshi
Ranch Hand

Joined: Nov 12, 2003
Posts: 54
thank you!
I agree. Here's the link:
subject: circular object reference
It's not a secret anymore!