How to Find Unwanted References in Android Using Android Profiler - android

I'm trying to get better at hunting down memory leaks in Android.
I have discovered the Android Profiler and learned how to perform a heap dump and how to determine if there are too many instances of a given object in memory.
I have read that one of the ways to get to the root of why an unwanted object is still hanging around is to highlight it and "look at what objects are still holding references to it and trace your way back to the original cause."
So... in this screenshot you can see the undesirable situation: I have three instances of MainActivity... and all three of them have a number in the "depth" column signaling they are really leaks.
If the object in question were a class of my own creation, then the process would be more straight-forward, but since we're dealing with an actual Activity here, when I highlight any one of the three, there is a massive list of objects referencing it (the list goes far beyond the screenshot).
Surely most of these are normal/benign references -- How am I supposed to tell which ones are worth investigating?
What are the clues? Is it the " this$0 " ? Or the massive number in the retained column? A depth number matching the object in question? I'm just guessing at this point.
Surely I'm not expected to go through the entire list mulling to myself, "Nope... can't be that one... that's a normal part of Android Framework X,Y, and Z..."

I'm trying to get better at hunting down memory leaks in Android.
I will give couple of examples but first, due to the number of questions you asked that is not related to your topic
I will first explain what you see in "Instance view";
Depth: The shortest number of hops from any GC root to the selected instance.
0 is for "private final class" or static members
if it's blank it's going to be reclaimed - which is harmless for you
Shallow Size: Size of this instance in Java memory
Retained Size: Size of memory that this instance dominates (as per the dominator tree).
Is it the this$0?
this$0 is a synthetic variable generated by the compiler which means "one level out of my scope", it's a parent object of a non-static inner class.
How am I supposed to tell which ones are worth investigating?
It depends, if the depth is 0 and it's your code - investigate, maybe it's a long running task with bad end condition.
When analyzing a heap dump in the Memory Profiler, you can filter profiling data that Android Studio thinks might indicate memory leaks for Activity and Fragment instances in your app.
The types of data that the filter shows include the following:
Activity instances that have been destroyed but are still being referenced.
Fragment instances that do not have a valid FragmentManager but are still being referenced.
In certain situations, such as the following, the filter might yield false positives:
A Fragment is created but has not yet been used.
A Fragment is being cached but not as part of a FragmentTransaction.
Filtering a heap dump for memory leaks.
Techniques for profiling your memory
While using the Memory Profiler, you should stress your app code and try forcing memory leaks.
One way to provoke memory leaks in your app is to let it run for a while before inspecting the heap.
Leaks might trickle up to the top of the allocations in the heap.
However, the smaller the leak, the longer you need to run the app in order to see it.
You can also trigger a memory leak in one of the following ways:
Rotate the device from portrait to landscape and back again multiple times while in different activity states. Rotating the device can often cause an app to leak an Activity, Context, or View object because the system recreates the Activity and if your app holds a reference to one of those objects somewhere else, the system can't garbage collect it.
Switch between your app and another app while in different activity states (navigate to the Home screen, then return to your app).
A growing graph is a big indicator
If you observe a trend line that only keeps going up and seldomly goes down, it could be due to a memory leak, which means some pieces of memory cannot be freed. Or there’s simply not enough memory to cope with the application. When the application has reached its memory limit and the Android OS isn’t able to allocate any more memory for the application, an OutOfMemoryError will be thrown.
Turbulence within a short period of time
Turbulence is an indicator of instability, and this applies to Android memory usage as well. When we observe this kind of pattern, usually a lot of expensive objects are created and thrown away in their short lifecycles.
The CPU is wasting a lot of cycles in performing Garbage Collection, without performing the actual work for the application. Users might experience a sluggish UI, and we should definitely optimize our memory usage in this case.
If we are talking about Java memory leaks
public class ThreadActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
new DownloadTask().start();
}
private class DownloadTask extends Thread {
#Override
public void run() {
SystemClock.sleep(2000 * 10);
}
}
}
Inner classes hold an implicit reference to their enclosing class, it will generate a constructor automatically and passes the activity as a reference to it.
The above code is actually
public class ThreadActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
new DownloadTask(this).start();
}
private class DownloadTask extends Thread {
Activity activity;
public DownloadTask(Activity activity) {
this.activity = activity;
}
#Override
public void run() {
SystemClock.sleep(2000 * 10);
}
}
}
In a normal case, the user opens the activity wait 20sec until the download task is done.
When the task is done the stack released all the objects.
Then the next time the garbage collector works he will release the object from the heap.
And when the user closes the activity the main method will be released from the stack and the ThreadActivity also reclaimed from the heap and everything works as needed without leaks.
In a case that the user closes/rotate the activity after 10sec.
The task is still working that means the reference for the activity still alive and we have a memory leak 💣
Note: when the download run() task is done the stack release the objects. so when the garbage collector works next time the objects will be reclaimed from the heap because there is no object referenced on it.
related Youtube playlist
And https://square.github.io/leakcanary/fundamentals/ is great.

Related

Is "leaking" context inside AsyncTaskLoader that bad?

I have an AsyncTaskLoader that does some background task. While doing this task, it needs to access some views. (No I can't just get the values of the views beforehand - they are custom views, with some magic stuff attached to it - please just accept this)
However, this is causing a context leak because the AsyncTaskLoader is holding a reference to a Context object.
Question 1) Are context leaks that bad? (my loader runs only for 100ms - 200ms)
Question 2) Is there a way to hold a view without a context leak (I'm pretty sure not so this is just wishful thinking)
It's not that bad, right? Like the old views are garbage collected a fraction of a second later.- that's the only side effect, right?
For the record the view I need a reference to is CropImageView from https://github.com/ArthurHub/Android-Image-Cropper and the method I need to call from inside the Loader is view.getCroppedImage(width, height, CropImageView.RequestSizeOptions.RESIZE_INSIDE);
(no I can't use the prepackaged async versions of getCroppedImage because of reasons)
Yes, even minor leaks are dangerous because you'll never know how much memory it might leak. In your example, when any of the background tasks is holding the reference to context, it won't allow context to be garbage collected thereby leaving a wasted memory. This is fine for small objects but giant objects like context, Bitmaps holds tons lot of memory without letting it collected by GC.
Assume, you started a Loader from Activity A,
A -> x memory ( x ~ very large memory comparatively )
While still, the loaderis in progress you changed the orientation of mobile, which creates a new instance of Activity A with the same amount of memory x. Ideally old instance of Activity A should be garbage collected but GC can't recollect old instance memory as it is Strongly referred to a background task.
Hence, you need to take care of leaks while performing background tasks, this can be done in two ways -
either cancel the loader on destroying the activity instance (or) pass weak reference of your context to a loader.
Yes context leaks is bad,we have to avoid it manually.AsyncWork holds the reference to the Context, the Context cannot be GCed until the task is complete: the Context memory leaks. There are two solutions:
1.Use a context that is long-lived, anyway, the Application context.
2.Tie the life of the async task to the life of the context to which it hold a reference: cancel it in onPause().

Memory not freeing after fragment is removed

I have a Fragment which has a RecyclerView.
In this RecyclerView, I may occasionally download and display images (loaded with Glide into ImageView.
So when I open the Fragment, used memory may sometimes jump from around 30MB to around 100MB or even more.
After the Activity that is holding the Fragment is finished, the memory does not free up. It stays the same as before.
I checked Glide documentation and apparently we don't have to worry about freeing up Bitmaps in RecyclerView. This is a huge issue, because app often crashes due to OOM because of this.
How should I correctly handle freeing up memory when Fragment is removed?
Edit: another observation
Another thing I noticed is that if I finish the Activity and then start the same Activity again. Memory will jump back down for a moment and then back up to 100MB, which leads me to believe that the memory is cleared before launching the Fragment again.
Garbage Collection is sometimes a painful issue in Android.
Most developers fail to consider this issue and just keep developing without any sense of resource allocation.
This will of course cause memory problems such as leaks, OOM and unnecessary resource binding. There is absolutely no automatic way to free up memory. You can not, under any circumstances, rely solely on the Garbage Collector
Whenever you pass the Fragment's or Activity's onDestroy() method, what you can and should do is erase any construct that shall no longer be required in the application. You can do the following :
Avoid anonymous instances of listeners. Create listeners and destroy them when you no longer need them.
Set all the listeners (be them click, longclick, etc) to null
Clear all variables, arrays. Apply the same procedure to all the classes and subclasses contained inside the Activity/Fragment
Set the variable to null whenever you perform any of the previous steps on that given class (applies to all variables)
What I ended up doing was creating an interface like
public interface clearMemory(){
void clearMemory();
}
and implementing it on every class, be it Activity, Fragment or a normal class (includes adapters, custom views, etc).
I would then call the method whenever the class was to be destroyed (because the app was being destroyed or whenever I felt need to do so. Careful not to dispose in normal runtime)
#Override
public void onDestroy(){
clearMemory();
}
public void clearMemory(){
normalButtonOnClickListener = null;
normalButton.setOnClickListener(null);
normalButton = null;
myCustomClass.clearMemory(); // apply the interface to the class and clear it inside
myCustomClass = null;
simpleVariable = null;
...
}
By implementing this in a systematic way, my applications' memory management has become easier and leaner. One can then then know/control exactly how and when the memory is disposed.
This is adding on to Ricardo's answer.
You can add the following code to initiate garbage collection in Android:
Runtime.getRuntime().gc();
Note: Call this function after you've made all local variables null. Execution of this code doesn't guarantee that the system will garbage collect on your app, it merely hints that it might be a good time to do it.
I've used this in all my activities' onDestroy(), and it always seems to work when I want it to.
Give it a try, it might help you out.

What's exactly a memory leak in this case?

To clear all background activities I did the following:
I kept a static array list, and whenever I used to go from one activity to another, in the onCreate() method of new activity, I added the object of current activity into that list like this:
SomeClass.addActivity(CurrentActivity.this);
I added the above statement in each activity.
The addActivity():
public void addActivity(final Activity activity) {
activityList.add(activity);
}
And when I wanted to clear the stack, I called:
public boolean clearStack() {
for (Activity activity : activityList) {
activity.finish();
}
activityList.clear();
return (activityList.isEmpty());
}
In this way, I cleared my activity stack.
But it produced a memory leak. It's not the right way to do that. It's not ok to hold references to activities. Can you guys explain me why and how exactly memory leak occurred in this case?
I used MAT for eclipse to find this memory leak in my app.
Any help would greatly be appreciated.
Holding references to activities outside their context (when they are in background or "closed"/finished) causes memory to leak - the Android operating system would like to clear from memory "old" activities when it decides it's the time to do so (You can't control it manually).
In that case - the garbage collector would try to free the activity / activities from memory, but because something (your array of references to activities) is holding a reference to it - it can't be garbage collected, so it can't free it from memory- and that's a sample of a memory leak.
This document describes how to avoid memory leaks:
http://android-developers.blogspot.co.uk/2009/01/avoiding-memory-leaks.html
Try rotating the device a couple of times and see what happens- you'll eventually run out of memory because you're still holding a reference to previous contexts which the GC can't clear.

Should I null references to Activity Context, when my Activity finishes?

Is it a good practice to null references to Activity Context, when my Activity finishes? I have 3 AsyncTask's, each of them can be running in several instances simultaneously. The update the UI in onPostExecute(). Nulling all Activity Context references in onDestroy() would be quite difficult and make the code messy. What is the best thing to do?
Check WeakAsyncTask for an example from Google of an asynctask that doesn't keep references alive beyond the activity lifecycle, and BetterAsyncTask from DroidFu for an example of a way to wire AsyncTasks so they can reconnect to new activity instances (after a rotation, for example); usage example is here.
There's probably not too much harm in keeping the references to Activity around for a short operation (e.g. a single small web request or small file write), but if there's the possibility for the tasks to pile up, it could cause a problem. For example, if your app reads a 200KB XML file from a server on creation, which let's say can takes 1 minute or more over EDGE, a quick flip of the phone open/closed 3 or 4 times could lead to 4 retained Activity instances -- you can run out of memory pretty quickly in this situation, not to mention the duplicated work.
For any really long-running processes, though, you should definitely consider an IntentService instead of an AsyncTask. They're designed for longer-running processes that aren't really tied to a specific activity - like how you can send an MMS and leave the activity to go do other things, and you get a nice happy toast informing you of the completion of the task whenever it finishes.
Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself). Try using the context-application instead of a context-activity. Nulling the references is not needed when you do not need the opposite because of the memory troubles.
If the tasks will be eligible for garbage collection themselves shortly after your Activity finishes, I see no problem in keeping the references around.
If the tasks do outlive the activity for a significant amount of time, you should set all references to the Activity Context to null. See also the article Avoiding Memory Leaks.
Either way, it is good practice to use the Application Context (getApplicationContext()) instead of the Activity Context whenever you can. In this case you can't do this, because you need to post UI messages; I'm just mentioning it for completeness.
You can hold context reference using Weak reference. http://developer.android.com/reference/java/lang/ref/WeakReference.html
Weak referenced objects can be GC'd. You should just do check if you context reference is still valid every time you use it.

Android: removing/destroying objects when screen is rotated

I am finding that performance degrades after one or more screen rotations, and I presume that this is likely to be because an App's main Activity is destroyed and recreated each time the screen is rotated and that my app must be leaking memory when that happens.
I have read that, contrary to what one might expect, not all the objects created by an app's main Activity (or in classes called by that Activity) are destroyed when the activity is destroyed. Specifically, I think I have read (although I can't now find where) that if the View uses a large bitmap member object then the Activity's onDestroy() method should be over-ridden and the bitmap should be explicitly recycled.
Are there other objects that need to be destroyed or removed when the Activity is destroyed? What about Listeners? Is there a comprehensive tutorial or guide on this subject?
Is there a comprehensive tutorial or
guide on this subject?
Not really.
Are there other objects that need to
be destroyed or removed when the
Activity is destroyed? What about
Listeners?
Bitmaps are unusual, in part because they use memory outside of the 16MB heap, if I understand the byzantine Android memory model correctly.
Beyond large bitmaps, the biggest thing you really need to worry about are things that prevent normal garbage collection from working. Anything that holds onto the activity, directly or indirectly, from a static context will keep the activity from being garbage collected. Examples include:
static data members on classes (e.g., you rig up your own listener framework with one of your services, so your service holds onto a listener which holds onto your activity)
threads (e.g., you manually fork a background thread and do not terminate it)
Note that putting android:configChanges="orientation" in the Manifest prevents the Activity from being destroyed when the screen is rotated. So I no longer need to worry about whether I need to destroy or remove individual bitmaps or other objects! (Thanks to Ribo for pointing this out on another thread.)

Categories

Resources