Android memory leak with static final

android, memory-leaks, static

Solution

This information is incorrect. Making a variable static final will not cause any kind of memory leaks just because it was marked static final. That is not to say you can't create memory leaks by doing that though. One thing you want to make sure to avoid is creating a static variable that is of type context (such as activity). When you create a static reference to a context you are possibly creating a memory leak. A static variable means there is only one copy of that variable for your entire application and across instances of that class. It also means that it will remain in memory until it is explicitly cleared or the application is shutdown. Static variables are class level variables and are not attached to any specific instance of an object. When you create for example a 'public static final string myString = "Hello"' you will never be causing a memory leak. This way of define a constant will actually save memory vs using 'public final string myString = "Hello"' because without static a memory location will be created to store that string for every instance of this class instead of just having one copy for all instances to use.

Problem

The question is on using static final constants which apparently causes memory leaks: I have been searching for information on how not to cause memory leaks in Android Apps. One big problem is using private static final for constants. Apparently that is how constants should be defined. But static final means it hangs around after a rotation and means the Activity cannot be cleared. Obviously I am misunderstanding something. I know that putting variables in the Application context allows them to hang around without causing problems. As a general question on memory leaks: There are lots of information on memory leaks, but I cannot find anything that sums up all the information clearly. Any recommendations where it is all fully explained.

Original source