Understanding Garbage Collection in android - android

I Think i Need Some Help to Understand Garbage Collections, well i know garbage collection clears those who have no referrence from a live Thread, so for example i have a class that Decodes images like this:
new ImageDecoder(MyImageView).Decode();
do i need to keep a reference to the ImageDecoder class and null it later, or it will recycle whenever i call MyImageView.setBackgroundResource(0); ?
or whenever that i create a reference to a class and that Class adds tons of stacks, so whenever i do
MyClass aClass;
...
aClass = null;
Then the Heap Should be Freed From all Heap that Class Took according to the Articles, But It doesnt Happen in real life as i see , how is that working?
thanks alot;

You cant controll in Java and same applies here. Assigning aClass = null doesnt mean GC will run immediately and free memory on heap. It will run when he thinks JVM is running out of memory and creation of new objects require more space then it may run which in case my stop your main thread and freeze your app.
Oracle Java GC Basics

Related

Why is this a memory leak

I came across a library for memory leak detection in Android (Java) called LeakCanary but cannot understand the example where they leak the memory. Could anybody please explain how and why the code shown in their example is a memory leak.
class Cat {
}
class Box {
Cat hiddenCat;
}
class Docker {
static Box container;
}
// ...
Box box = new Box();
Cat schrodingerCat = new Cat();
box.hiddenCat = schrodingerCat;
Docker.container = box;
and then they watch the variable schrodingerCat for leaks which gives a leak shown as follows (which I dont know how to relate to the above code).
* GC ROOT static Docker.container
* references Box.hiddenCat
* leaks Cat instance
Any help with the explanation of the leak and how the detection relates to it would be very helpful. Also some good articles for beginners would be nice.
Thanks!
First, let's understand what is a Memory Leak:
Definition
Memory Leak is data allocated (bitmaps, objects, arrays, etc) in the RAM that the garbage collector (GC) is unable to free, although it is not needed anymore by the program.
Example
A user is opening a view that shows an Image. We load the bitmap to the memory. Now the user exit the view and the image is not needed anymore and there is no reference to it from the code. At that moment the GC comes into action and remove it from the memory. BUT, if we still had a reference to it, the GC will not know it is OK for removal and it would have stayed in the RAM taking unneeded space - aka Memory Leak.
Cat in A Box
Let's say we have a Cat object in our app, and we hold it in a Box object. If we hold the box (have a reference to the Box object) and the Box holds the Cat, the GC will not be able to clean the Cat object from the memory.
The Docker is a class that has a Static reference to our Box. This means that unless we nullify it, or re-assign the value, the Docker will keep referencing the Box. Preventing the Box (and the inner Cat) from ever being removed from the memory by the GC.
So, do we need the Cat? is it still relevant for the App?
This is up to the developer to decide how long we need the Cat for. LeakCanary and other diagnostic tools suggest of a possible Memory Leak. They THINK that the object (Cat) might not be needed anymore so they alert that it is a leak.
Recap
In the example, they give a common scenario of a Memory leak. When using a Static reference we prevent from the GC to clean an Object. You should read this:
* GC ROOT static Docker.container
* references Box.hiddenCat
* leaks Cat instance
as:
Object Cat might be not used anymore but was not removed from memory by the GC.
The reason the object Cat was not removed is since Box is having a reference to it.
The Reason the object Box was not removed is since the Docker has a static reference to it.
Static reference by Docker is the ROOT of the tree that causes the possible leak.
It looks like the RefWatcher instance used to "watch the variable schrodingerCat for leaks":
refWatcher.watch(schrodingerCat);
forces a set of GC passes and if the reference passed in isn't collected during those GC passes it's considered a leak.
Since the static Docker.container.hiddenCat is keeping a GC rooted reference to the object originally known as schrodingerCat, it can't be GC'ed so when you ask RefWatcher to check it. Therefore it lets you know that the object can't be collected.
I suggest you read this answer https://stackoverflow.com/a/11908685/1065810
It will probably help you understand the example above.
In brief, in your example, the class Docker keeps a reference to a Box. Even when the container box is not needed anymore, the class Docker still holds a reference to it thus creating a memory leak.
Let me know if that helps.

Logic behind memory leak in android

Normally in c++ what memory leak is , If we have alloted an object like
Obj c = new Obj();
then if we do
c = b; (example)
we lose the pointer to the object c that's the memory leak.
Question:
But in android Garbage collector collects object when there is no pointers pointing to them. So why there is memory leak even after that ?
Update
All the answers points to holding reference to unused objects is causing memory leak. Thats right. But is that the only cause of memory leak. Holding pointers will be released when activity is finished unless it is static. There are bitmaps and other memory hunger objects , don't they cause any problems in this
In Android/Java memory leak occurs
when you are keeping the reference of an object/instance even after it is no longer required.
when you keep open a file stream, when you are done with it.
Unclosed connections
There are other reasons for memory leak as well, but these are the most common ones.
In garbage collected runtimes, a memory leak means that an object cannot be collected even if it is no longer used. For example, a reference is held to an object but the reference is no longer used for anything.
Casually, the term memory leak is used to refer to situations where these incollectible objects keep on accumulating, increasing the allocated heap size and eventually leading to OOM.
There might be a leak when a Context (an Activity, Service, etc.) is retained by any helper class that would have a reference to it.
Illustration: instead of this:
public class Helper {
private static Context mContext;
public Helper(Context context){
mContext = context;
}
public static void methodDoesSomething(){
...
}
}
Use the context without retaining it by passing it as a parameter:
public class Helper {
public static void methodDoesSomething(Context context){
...
}
}
Because Android will want at some point to destroy an Activity for instance, and an object has a reference to it, The Garbage collector can not remove that Activity thus we have a memory leak.
The answer is partially in your question: Precisely because those references are not freed. Suppose a situation where you have an instance of a class, you've ended working in it but for certain circumstances, the instance keeps there in a state it's not freed. Additionally to Garbage Collector unability to free it, if not controlled, the amount of memory may even increase if it's not handled.
There is one additional thing too. You may have a code that looks correct and well written, but when you instantiate some native libraries, that means you're referencing an hierarchy of classes. If you're not aware of what are you doing, you may precisely handle incorrectly some references and lead to memory leaks. One very popular example is keeping a Context reference into your class. The context instance is never freed and a reason of huge memory leaks.
There are solutions for this, additionally to the obvious (free objects when you're done, etc.). In Java there are SoftReferences, WeakReferences, and other. This objects are containers that tell the Garbage Collector that they have preference on being freed once unused or there are no other references pointing to them. So you're helping the GC to know what should be freed. They're dangerous at a certain point in Android environments, as apps are limited too 16MB of heap, so a WeakReference might be collected too fast. It's necessary to check whether the object still exists.
I think we need to define "Memory Leak" in the first place. Memory leak is something you don't need anymore but it still in the memory and each time a new object is created, a new place will be allocated in the memory. The application will hold more and more memory in time.
private static Drawable background;
#Override
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(this);
background = getDrawable(R.drawable.large_bitmap);
label.setBackgroundDrawable(background);
setContentView(label);
}
Above example, TextView get Activity as reference, which is a link between
TextView and Activity
now, then there is a static variable
background
which holds the background drawable, static variable will be alive until the application is destroyed or finished. Imagine that you want to destroy the activity, when you destroy static variable will still hold a link to activity, because of that garbage collector won't be able to collect it.
You can have a look at here about more.

Java android optimization. Non-static or static method?

I have a static class with a method in it that I run a few hundred times. Currently, everytime the method is run, it creates two different stack objects. If I were to make that class non-static so I can create the two stacks on construction and then reuse them by clearing them, would it be quicker? I guess the answer depends on creating a new stack object vs clearing an existing one (which is likely empty anyway) and if the performance gain (if any) from clearing it instead is greater than the performance loss from having a non-static method.
I've tried profiling the two and it never seems to work, but that's a different question.
It depends on how you use static variables and method in your code.
Instance variables and objects are stored on the heap.
Local variables are stored on the stack.
Static variables are stored in a permanent area on heap. The garbage collector works by marking and sweeping objects. Static variables cannot be elected for garbage collection while the class is loaded. They can be collected when the respective class loader (that was responsible for loading this class) is itself collected for garbage.
If i have a value to be passed to another activity i would use intents instead of static variables.
In a custom list adapter we use a static viewholder. So using static variables or methods depends on different situation.
You can analyze memory usage by objects using a tool called MAT Analyzer. The video in the below talks about memory management and how to detect and solve memory leaks
http://www.youtube.com/watch?v=_CruQY55HOk.
MemoryInfo mi = new MemoryInfo();// current memory usage
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
http://developer.android.com/training/articles/perf-tips.html. Have a look at this link for performance tips especially the topic under Prefer Static Over Virtual.
Memory availabilty is one of the criteria's to be considered using static variables and methods for performance and avoiding memory leaks.
This is really a question about trying to reuse objects. You can reuse objects in a static method too if you declare a static member. Separately: yes it's probably better to design this without static anything.
In any event, the upside to reuse is avoiding object creation. You still pay some cost of "clearing" the object's state. Or else, you risk memory leaks in the case of something like a Stack.
There is an ongoing maintenance issue: you add new state to the object, and, did you remember to update the method that clears it?
You also need to now synchronize access to this method or otherwise prevent two threads from using it at once. That could introduce a bottleneck as threads can't execute the method concurrently.
You also always pay the memory cost of this object living in memory for the entire runtime.
In the olden days, people would create object pool abstractions to avoid recreating objects. This has its own complexity and runtime overhead, and are generally well out of favor, since the cost of creating an object and GCing it is so relatively small now.
Trying to reuse objects solely for performance is rarely a performance win. It would have to be in a tight loop and not suffer from several possible problems above to be worth it.

DDMS Heap - 1-byte array(byte[], boolean[])

I experience some memory leaks in my android application. I've already used MAT to analyze the memory usage. But I have one question from the DDMS perspectiv in Eclipse, what does 1-byte array[byte[], boolean[]) mean?
Is this specific for my application? You can see that this is the big memory leak issue, this always increases in size, and the rest will increase and decrease randomly. My guess is that the GC doesn't catch this type. Can anybody explain why this happen, with this little information?
One byte array is the designation for any data structure that is organized as a single byte array. In you case and with that size, I would bet in a Bitmap or a Drawble.
Most common reasons for memory leaks are static object not properly managed and holding references to:
Context
View (which holds reference to context (and possibly also to bitmap)
Thread (which are not easly collected by GC)
Handler (which holds reference to context)
Most of them can be solved ensuring that you set the object to null when it's no long required.
Regards.
A byte and a boolean are each 1 byte. If you have an array of those you have a "1-byte array".
A ByteBuffer for example should internally hold one of those.
You have a total of 614 of them where the smallest one be a byte[24] (or boolean[24]), the largest one is 3MB. All of them together use 104MB.
The GC will get rid of them if they are no longer referenced.
For example when you put
private static byte myArray[] = new byte[3 * 1024 * 1024];
in one of your classes and never set it back to null (myArray = null) then this one can't be garbage collected because another Object has a reference to it. The object would be the class itself (as in String.class). The class object can't be garbage collected since classes are never unloaded. (they are referenced by their ClassLoader which could itself be referenced / loaded by another ClassLoader and you can't create Objects & use classes without them - they need to stay and they need to keep a reference to their classes)
It's usually not that simple but often start with static somewhere.
Within MAT (after you force GC) look at the reference chain for the objects that are no longer intended to stay alive and identify the one Object that holds the reference. Set that one to null in your code and your leak is gone. Explained in more detail here:
http://android-developers.blogspot.de/2011/03/memory-analysis-for-android.html
I ran to this problem tonight and almost I checked every bit of code but I couldn't find anything.
What I did was starting the app from intelij and then pressing home button and open the app again. Every time the app heap was doubled.
Finally I discover when I launch the app from ADB and press the home button and open the app again it doesn't bring back the old activity, it just start a new one. When I pressed finish it starts to cycle through all of them. It's like they are treated as two different intent. So I put android:launchMode="singleTop" on the main activity in manifest and it resolved the problem.
Although it's not the main cause of this problem but if you encountered this check this out before anything. It wasted three or four hours for me.

does android.media.SoundPool cause memory leak?

I found these code may case memory leak on android 2.1
SoundPool soundPool = new SoundPool(10, 7, 0);
...
...
soundPool = null;
every time after the execution, the MAT pluging tells that two String objects of "android:unnamed_thread" are added to the heap of the process. is that an issue?
did you try to run soundPool.release() instead of soundPool = null?
I see two possibilities (there may well be more).
The first (most likely) is true of all Java objects: just because you set the reference to null doesn't automatically mean that the object behind it will be garbage-collected.
If a SoundPool object itself contains a reference to the two thread objects, none of the three will necessarily be GC'ed until space is required (although that depends, of course, on how aggressive your collector is).
The second (less likely) is that Android may be smart enough to cache thread (or even SoundPool) objects in case they need to be used again. They may nave done this as a performance optimisation if object creation is more expensive than object re-cycling.
In that case, they would still have a reference to the objects somewhere in a cache and they wouldn't be considered eligible for garbage collection.

Categories

Resources