Re: [java-gnome-hackers] WeakReferences going away
Brought to you by:
afcowie
From: Tom B. <Tom...@Su...> - 2003-02-27 18:10:27
|
On Thu, 2003-02-27 at 09:20, Philip A. Chapman wrote: > The original thought was to protect from memory leaks. Yes, dangling listeners can be a major source of object leaks. > The problem is that sometimes developers do not call the remove method > to remove their listener before releasing all other references in their > code to the listener object. This leaves the reference in the listener > list as the only reference to the listener and the listener is never > garbage collected. > > Granted, this is a developer issue in that they *should* always call the > remove method first. The hope was to give some protection against such > sloppy programming from causing big problems. Paranoid, perhaps, not altruistic. :-) One way to solve this is to provide good example code -- developers tend to slavishly copy examples, and as we learned the hard way with Swing, bad examples foster widespread bad toolkit use. In this case, I think the problem is related to my style of app development: I never keep listener references in my app, but instead just attach them to a widget and forget about them: Button cancelButton = fontsel.getCancelButton(); cancelButton.addListener(new ButtonListener() { public void buttonEvent(ButtonEvent event) { if (event.isOfType(ButtonEvent.Type.CLICK)) { fontsel.destroy(); } } }); In this example, the only reference to the ButtonListener is in cancelButton's listener list, which is why it gets GC'd if that list is implemented with WeakReferences. This style of listener usage is very common among AWT and Swing developers; that doesn't make it necessarily correct usage, but I can testify that it is bewildering for such a developer to have one's listeners "disappear" after installing them this way. Now, if an application class either implements the listener interface directly or stores the reference, then you have the potential leakage you describe since the app instance won't be GC'd. But there I think good documentation is the best one can do here. > If it's causing too much trouble, can it be reworked? If not, I'd say > remove it. Maybe the idea was too altruistic. If memory isn't too big an issue (or if we want to create a "debug" version of our libraries), we can keep a WeakReference'd static list in each listener class of the current listeners and what widget they are listening to. Some key sequence (such as Ctl-Shift-F10) can trigger the dumping of this list out to the command line for debugging purposes. This beats poking around in a heap profiler, and is much more likely to be used by app developers. If you want, I can add this feature soon. Tom |