One of the core benefits of Java that she is a garbage-collected language. That means we can create objects, and the garbage collector will take care of allocating and freeing up the memory for us.

Although we have the garbage collector, unfortunately, we can prevent him from doing his job by making some code mistakes. Those mistakes are causing memory leaks. The leaks can affect our android app by wasting unreleased memory and eventually causes to out of memory exceptions and lags.

What is Memory Leak?

Failure of releasing unused objects from the memory

That means there are unused objects in the application that the garbage collector cannot release from memory. So the memory unit is occupied until the end of the application/method.

Wait!!

Before jumping to the context, let’s start with the basics.

What is RAM/Memory?

RAM, or Random access memory, is the memory in android devices or computers that used to store current running applications and their data.

I’m going to explain two main characters in the RAM, first is the Heap, and the second is the Stack. Are you ready? Let’s move to the fun part.

What’s Heap & Stack?

I’m not going to make it to long, so a short description, the Stack is used for static memory allocation while the Heap is used for dynamic memory allocation. Just keep in mind that both the Heap and the Stack are stored in the RAM.

So how does it works in the real world?

Let’s explain the stack and heap usage with a simple program.

Program

The image below shows how do the stack and heap look like and where they refer to when we start the program.

Let’s go together over the program execution, and stop each line, and tell how do is it works. And explain when the stack and the heap need to make allocations and when they are freeing up the memory.

Line 1 — The java runtime creates a stack memory that is going to be used by the thread of the main method.

Line 2 — Here we are creating a primitive local variable. That is created and stored in the stack memory of the main method.

Line 3 —We are creating a new object. The object is created in the stack and stored in the heap. The stack is storing the reference of the object to the heap. We are calling it a pointer.

Line 4 — The same as line 3.

Line 5 — A new block created in the stack. That is going to be used by the foo method thread.

Line 6 — Here we are creating a new object for the `param` object in the stack memory of the foo method. That pointed to the address of the original object in a heap.

Line 7 — We are creating a new object. The object created in the stack and pointed to the string pool in the heap.

Line 8 — In the final line of the foo method, the method terminated. And the objects will be released from the stack block of the foo method.

Line 9— The same as line 8, In the final line of the main method, the method terminated. And the stack block of the main method becomes free.

You are asking yourself, what about freeing up the memory from the heap? Right? Grab a coffee☕️, and keep going.😼

What happens when methods terminated?

Every method has there owned scope. When the function terminated, the objects are released and reclaimed automatically from the stack.

figure 1

In Figure 1, when the foo method terminated. The stack memory or the stack block of the foo method will be released and reclaimed automatically.

figure 2

In Figure 2, The same. When the main method terminated. The stack memory or the stack block of the main method will be released and reclaimed automatically.

Conclusion

Now, we understand that the objects in the stack are temporary. And they will be released and reclaimed when the method terminated.

What about the Heap?

The heap is different from the stack. For releasing and reclaiming the objects from heap memory, we need help.

For that, Java has made a superhero for helping us. We called it the Garbage Collector. He is going to do the hard work for us. And caring about detecting unused objects, release them, and reclaim more space in the memory.

How does the garbage collector work?

Simple. The garbage collector is looking for unused or unreachable objects. What does that mean? That means if there is an object in the heap that does not have any reference pointed to it. The garbage collector will take care of releasing it from memory and reclaim more space.

What happens when the garbage collector works?

Figure 3

I am taking Figure 2 as an example. When the garbage collector starts and doing the hard work, the result should look like the image above Figure 3. He will release and freeing up the objects from the heap.

Now you are saying. Ok, amazing! But how do the memory leaks happen, if the garbage collector is doing the hard work and looking for the unused object and release them? Let’s find out. 😃

How do memory leaks happen?

It happened when there are unused objects in the heap memory. That somehow some objects from the stack are still pointed/referenced to it.

There is a simple visual representation in the image below for a better understanding of the concept.

In the visual representation, what we are seeing is that when we have objects that been referenced from the stack but not in use anymore. The garbage collector will never release those objects or freeing up the memory, cause it looks like those objects are in use while they are not.

How we can cause a leak?

There are various ways to cause a memory leak in Android. And it can be made easily using AsyncTasks, Handlers, Singleton Classes, Threads, and more. I’m going to explain how we can cause a leak using threads or singleton, and how we could fix and avoid them.

Check out my repository in Github. There I have code examples of how we can cause a memory leak and how we can avoid and fix them using the AsyncTask, Handlers, …etc.

Examples:

1. How can we cause a leak using thread?

We gonna create a thread who run a task in the background that takes 20sec.

As we know 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.

Let's wear our secret glasses to see the class in a different way, how it really looks like.

That’s how the class looks like after wearing the glasses, You can notice that we have the activity reference inside the class.

So what happens when the thread starts?

In a normal case, the user opens the activity wait 20sec until the download task is done.

Task Running

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.