I want to assign a listener to a swing component that is not an inner class instance of the component, but needs a reference to it (passed via the listener constructor). Eg:
This strongly implies a circular reference to me. After looking around online, it seems to me that circular references are not such a big deal in java because major implementations do not use reference counts for GC. Also, this is a GUI where the component and the listener will exist for the lifetime of the process, so any circularity or GC issue with them is irrelevant.
However, it's important that I use best (or at least, not glaringly poor) practices in the code regardless of what I consider the significance to be at this point. So:
1) is that really a circular reference?
2) if so, do I have to avoid it (eg, by subclassing the component to include the listener as an inner class)?
Post by:Marcus Kelvin
, Ranch Hand
Actually, I just realized I can cast the component returned by getComponent() in the listener, so I don't need to keep a reference to it.
Which solves the problem but if anyone has any thoughts about the significance of circular references in java I'm all ears.
Post by:Martin Vajsar
Modern GC's don't mind circular references. These are all too common (eg. a linked list), so GC's cannot afford not to handle them well.
Actually, an instance of an inner class contains an implicit (hidden) reference to the outer class, so if you "avoid" circular reference by using inner class, you've probably not avoided anything. This also means that circular references are much more common than it seems at the first blush.
Edit: summary of the above is "there is no issue with using circular references in Java".
This thread has been viewed 611 times.
All times above are in ranch (not your local) time.
The current ranch time is Oct 17, 2018 13:03:31.