Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leakage in event listener

I have gone through the article http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html. In this article it is suggested to use a static inner class with a WeakReference . Many inner classes are used for event listeners. Can those inner class also cause memory leaks? Should those inner class be static?

like image 898
dev_android Avatar asked Feb 15 '11 10:02

dev_android


People also ask

What is the main cause of memory leaks?

A memory leak starts when a program requests a chunk of memory from the operating system for itself and its data. As a program operates, it sometimes needs more memory and makes an additional request.

What do you mean by memory leakage?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

What are memory leaks in JS?

What are memory leaks? In simple words, a memory leak is an allocated piece of memory that the JavaScript engine is unable to reclaim. The JavaScript engine allocates memory when you create objects and variables in your application, and it is smart enough to clear out the memory when you no longer need the objects.


1 Answers

Can those inner class also cause memory leakage?

Possibly. It depends on what those listeners are registered upon.

For example, a well-written OnClickListener for a Button should not result in a memory leak, because even though the OnClickListener may be an inner class and have an implicit reference to the Activity, the whole set of objects are all just tied to the activity. Hence, when the activity is destroyed, the activity, Button, and OnClickListener can all be garbage-collected as a whole.

However, a LocationListener, registered with the LocationManager system service, is held by the process. Hence, even if the activity is destroyed, the listener will remain registered. If that listener is an inner class, it will continue to hold an implicit reference to the activity, and you will have a memory leak.

Should those inner class be Staic one?

Possibly. In most cases, the right answer is "if you are registering a listener other than with the UI, be sure to unregister it at an appropriate point". In that case, there will be no leak.

Can any one give me any example code how the event listener can use leak-proofly.

Not in the abstract, no.

like image 121
CommonsWare Avatar answered Sep 20 '22 07:09

CommonsWare