Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid memory leaks in callbacks? [duplicate]

Tags:

java

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 ?

like image 514
Rishi Avatar asked Dec 12 '11 13:12

Rishi


3 Answers

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.

like image 117
Peter Lawrey Avatar answered Nov 19 '22 21:11

Peter Lawrey


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.

like image 1
OpenSauce Avatar answered Nov 19 '22 19:11

OpenSauce


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.

like image 1
belgther Avatar answered Nov 19 '22 20:11

belgther