Search code examples
androidmemorystatic-membersdalvik

How long do classes with static methods live in Android?


This is a follow up question to one of my previous questions.

I have a LoadingActivity which loads some graphics needed by all Activities and store it into a static class. I try to not load the LoadingActivity over again when pressing HOME and resume the app since it takes a lot of memory and runs out of it after several times whereby the graphics are already loaded, so no need to start the LoadingActivity again. My question is, how long does the static class live? Can I rely on it's availability after resuming the app, or may it be here since Android kills it due to memory issues or is it always here as long as the vm runs (that means as long as the phone is running)?


Solution

  • As Simon points out, "static class" means different things in different languages, and Java does not have anything quite like the static classes in some other languages. But I don't think that's what you're talking about. You seem to be asking whether objects referenced by strong static references can be garbage collected. If so, the answer is no.

    A class is represented by an object of class Class which is reachable via its ClassLoader. Anything referenced by the Class will therefore be reachable as long as the ClassLoader is reachable, which in the case of the system classloader is as long as the Java/Dalvik VM exists. But that is not as long as the phone runs, since an independent VM is created for each app. The entire process and VM in which an app is running may be killed whenever the app is in the background. When you return to the app, its classes will be reloaded.

    If static fields are really the best choice, as opposed to a ContentProvider or foregound Service, then every time your app resumes you will need to check if the static references have been initialized and re-initialize them if they are null.