Using static variables in Android

michael picture michael · Mar 19, 2010 · Viewed 82.8k times · Source

In android, are using static variables a recommended practice? E.g, implementing a Singleton pattern in Java, I usually do:

private static A the_instance;
public static A getInstance() {
    if (the_instance == null) {
       the_instance = new A();
    }
    return the_instance;
}

Also, when does this get cleaned up by the Android JVM?

Thank you.

Answer

Sean Owen picture Sean Owen · Mar 19, 2010

static fields are attached to the Class instance as a whole, which is in turn attached to the ClassLoader which loaded the class. the_instance would be unloaded when the entire ClassLoader is reclaimed. I am 90% sure this happens when Android destroys the app (not when it goes into the background, or pauses, but is completely shut down.)

So, think of it as living as long as your app runs. Is Singleton a good idea? People have different views. I think it's fine when used appropriately, myself. I don't think the answer changes much on Android. Memory usage isn't the issue per se; if you need to load a bunch of stuff in memory, that's either a problem or it isn't, regardless of whether you encapsulate the data in a Singleton.