Possible Duplicate:
How to avoid memory leaks in callback?
Effective Java says:
A third common source of memory leaks is listeners and other callbacks. If you implement an API where clients register callbacks but don’t deregister them explicitly, they will accumulate unless you take some action. The best way to ensure that callbacks are garbage collected promptly is to store only weak references to them, for instance, by storing them only as keys in a WeakHashMap.
I am unable to understand this. could someone explain this ?
If you add call backs to a collection, but don't remove them, this will lead to a memory leak. One way to handle this (apart from making sure such objects are always removed correctly) is to store the listeners in a weak collection. A weak collection can remove entries when that element/listener no longer has a strong reference.
The problem with this approach is you cannot have a listener which is only referenced in the collection as it will disappear randomly (on the next GC)
I tend to use listeners which are not referenced anywhere else and try to ensure unused listeners are removed correctly.
Holding a weak reference to an object does not prevent it from becoming garbage collected - if there are no more strong references to the object, eventually it will be garbage collected and you will no longer be able to access it via the WeakReference
you have stored. Google Java weak references tutorial
for more info.
It means: If a listener or callback references to the object itself, then the referenced object will never be GCed since the listener or callback is still there and there is a reference to the object from this, causing a memory leak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With