Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do listeners create memory leaks if not removed from a destroyed activity?

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?

like image 866
Spidy Avatar asked Mar 08 '11 21:03

Spidy


People also ask

What is the main cause of memory leaks?

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.

Which action causes memory leak?

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.

Do memory leaks go away when you close the program?

So technically the program terminates, but because it still resides on memory, any memory leak would not be released unless you unload the program.


2 Answers

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.

like image 147
maaartinus Avatar answered Nov 09 '22 22:11

maaartinus


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...

like image 3
Matthew Avatar answered Nov 09 '22 23:11

Matthew