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)?
The space for the static variable is allocated only one time and this is used for the entirety of the program. Once this variable is declared, it exists till the program executes. So, the lifetime of a static variable is the lifetime of the program.
A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.
Static data and static methods do not take up memory in individual instances.
1) Java static variable The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With