Skip to content Skip to sidebar Skip to footer

Is It Bad To Use Public Static Fields/variables?

I started learning about Android Development, and I read about static variables are bad and may leak memory because they are not garbage collectable. I've used some in certain situ

Solution 1:

Take a look at Avoiding memory leaks article on the Android Developers Blog. Keeping a static field holding a Context, or any other class that has a (strong) reference to a Context (such as any View) will mean that the garbage collector will not be able to reclaim the storage allocated by the Context. If the Context is an Application, thats OK because they live for as long as your app does and wouldn't be garbage collected anyway. But in case of Views, Context is likely an Activity which should be garbage collected as soon as possible.

That doesn't mean that all static fields will catastrophically leak memory. If they're primitive types, or simple classes, or even more complex classes with weak references to other classes, they might not prevent the garbage collector from reclaiming a lot of memory. But generally having static and especially public static fields is a code smell and should probably be avoided so the code is easier to maintain later.

Post a Comment for "Is It Bad To Use Public Static Fields/variables?"