# Memory Leaks in Android ###### tags: `Android` `Memory Leak` [TOC] ## What uses memory? 1. Objects 2. Threads 3. Processes :::warning **"Memory is FIXED amount"** This is known as the **HEAP**. In Android it represents the amount of free memory available at any given time. ::: ## What happens when we use part of memory? 1. A memory block is removed from the pile, HEAP. 2. This block will be used whether for an object, thread, process ## What happens when fixed memory is low or has not more space? When that happens, Android System Garbage Collector (GC) will go around the application and seek which object, process, threads are not longer being use. When found, it will clean and put the block back to the memory pile. ## GC and Memory Leak Relation Memory Leak happens when Garbage collector cannot reclame a resource and return it to the heap(memory pile). ## Why Memory Leaks happen? It usually happens when a View, Context or Activity Reference is saved in a background thread. **For example:** Let's say you have an activity which has an asynctask and have context inside. If you execute the background but then finish the activity before background finishes, then GC will want to collect the activity, however, it can't due to background service. Then memory leaks happen! ## Library to check out Memory Leak! **OpenSource:** leakcanary **URL:** https://github.com/square/leakcanary **leakcanary** helps you to understand where memory leak occurs and it will give a notification if problem occurs. ## Youtube Reference I learnt about memory leak from this video. If you want to further take a look about it, you can check the below URL. **URL:** https://www.youtube.com/watch?v=bNM_3YkK2Ws # Android Profiler: Detect Memory Leak