8

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 ?

Community
  • 1
  • 1
Rishi
  • 224
  • 2
  • 3
  • 11
  • This question is answered here. http://stackoverflow.com/questions/2859464/how-to-avoid-memory-leaks-in-callback – kensen john Dec 12 '11 at 13:53

3 Answers3

3

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

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.

OpenSauce
  • 8,533
  • 1
  • 24
  • 29
1

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.

belgther
  • 2,544
  • 17
  • 15