0

I have a class which has a static variable which holds Context reference.

public static Context context;

Android studio gives a warning saying that static references to the Context class leads to memory leaks

If I remove the static keyword, it does not give any warning.

Similar scenario with ContextWrapper class as well.

My understanding is, if we hold a reference to the classes which are related to Context will lead to memory leak. But, Why Android studio does not give any warning for non-static Context references?

I have seen some code examples where they have extended the ContextWrapper class. Whenever they needed the Context, they are accessing through the class which was extended `ContextWrapper'. Will this approach does not lead to Memory leak?

Also, Will memory leaks happens for non-static Context references at runtime? Did I understand it in wrong way? Am I missing something here?

Can anyone give explanation for this?

Thanks in advance.

Uma Sankar
  • 449
  • 1
  • 8
  • 19

1 Answers1

1

First things first, let's know about memory leaks and why it happens exactly

Memory leaks occur if there is any data in memory which can't be garbage collected ,Having said that, static variables can't be garbage collected as they stays live in memory throughout the Application life where as non-static variables can be garbage collected once it's enclosing parent is no longer referenced, keeping this in mind we'll see example to explain your question.

Consider class A with a static and non static Variable

Class A{
   private static Context iCanNeverBeDestroyed; 
     // Scope -> Application life, so memory leak can occur
   private Context iCanBeDestroyedWithA;  
      // Scope -> A
   private static int itWontMatterWhetherImDestroyedOrNot; 
     //Even though the scope is Application, due to low memory usage , memory leak is negligible in this case
}

Leakage is calculated based on scope of variable and size in memory together, high memory and greater scope has greater chances of leak, example like Context,Bitmap etc

Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
  • You mean If class `A` lives till the Application destroys, then this will lead to memory leak? – Uma Sankar Feb 14 '18 at 09:15
  • It doesn't work that way, Memory which is in use won't be garbage collected obviously and it's not considered as memory leak, if you are using only `A` throughout Application that won't be a leak, if you switched to `B` and `A` is not collected then it would be memory leak. – Rajan Kali Feb 14 '18 at 09:18