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.
Source: Tips4all
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.)
ReplyDeleteSo, 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.
I think static variables are OK.
ReplyDeleteThis is what Android doc says:
http://developer.android.com/guide/appendix/faq/framework.html
How do I pass data between Activities/Services within a single application?
A public static field/method
An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.
I'm not sure if such approach is good for mobile platform where you have limited memory available to you. Not to mention that the application will be run on a multi-tasking enabled device.
ReplyDeleteI think, this approach may hog memory from the device but I have no document to support this. Perhaps someone who's more educated than me can share their thoughts.
No. Don't do it! Use Google Guice (it works on Android, Java SE, Java EE, GWT, and is used in many Google applications, so you know it definitely works). To get started with Guice, watch the following:
ReplyDeleteJava on Guice: Dependency Injection the Java Way
Google I/O 2009: Big Modular Java with Guice
Singleton is a design anti-pattern, and you should consider using dependency injection, instead. These videos will explain why singletons are bad, and how you can avoid them using Guice.
In android, is it recommend to use
ReplyDeletestatic variable?
No (unless it's primitive finals of course).
If you absolutely need a Singleton, make a custom android.app.Application and store it there.