If you add a listener to a control/view and do not remove it, will that create a memory leak? For example, onCreate
adds a listener to an EditText
that listens for modifications. Do you need to remove this listener in the onDestroy?
I imagine that if you use an anonymous listener or a local variable that implements the listener, the memory would be free'd when the Activity
is destroyed due to scoping rules.
The only way I could see a memory leak potential is if the listener was passed in an intent object. Thoughts?
DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.
A Memory Leak is a situation where there are objects present in the heap that are no longer used, but the garbage collector is unable to remove them from memory, and therefore, they're unnecessarily maintained. A memory leak is bad because it blocks memory resources and degrades system performance over time.
So technically the program terminates, but because it still resides on memory, any memory leak would not be released unless you unload the program.
By themselves, listener do not create a memory leak. However, they're often used improperly and so may lead to leaks. Sometimes you see code where an object refers to a Component (e.g. for displaying messages there), which has a listener, which refers (possibly indirectly) to the first object. This forms a cycle and all its members live and die together. When the Component is a dialog which is meant to be short-living, you may have a problem. Beginners tend to use objects like
class MyKitchenSink implements Runnable, KeyListener, ....
which may have a lot of references and makes it easier to build a memory leak*. Not creating "universal classes" is the way to go.
* It's no "real" memory leak like in C
, since all the objects stays reachable and could be used if you wanted to. It's just keeping object reachable for a much longer time than expected, which eats you memory just like a leak.
A memory leak should not be created unless something other than the control/view references the listener - no need to remove the listener in the onDestroy...
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