简体   繁体   中英

Android Static Variable Scope and Lifetime

I have an application that has a Service that uses an ArrayList<Double> to store numbers in the background for a very long time; the variable is initialized when the service started.

The service is in the background, and there will be frequent access to the variable (that's why I don't want to use file management or settings -- it will be very expensive for a file I/O for the sake of battery life).

The variable will likely be ~1MB->2MB over its lifetime.

Is it safe to say that the variable will never be nulled by GC or the system, or is there any way to prevent it?

I have an application that has a Service that uses an ArrayList to store numbers in the background for a very long time

If "a very long time" is greater than "a handful of seconds, or as long as the user explicitly asks for it to be running", then we have problems.

Simply put, your service will not live "for a very long time". The user will kill it off with a task killer, or the user will kill it off with Settings application, or Android will kill it off due to excessive age. Too many developers are leaking services, causing degradations in device performance.

Very few services truly need to be running except for brief periods of time (eg, while downloading a large file) or at user request (eg, music player).

Is it safe to say that the variable will never be nulled by GC or the system, or is there any way to prevent it?

It will live as long as the process lives. The process will live until you stop the service (assuming there are no other components running), or until the user reboots their phone, or until any of the scenarios outlined earlier (eg, task killer) occurs.

Is it safe to say that the variable will never be nulled by GC or the system

Yes, as long as the variable can be accessed in your code, but this may be a good thing or a bad thing.

The "lifetime" of a static variable is that of the class -- "always and forever" while that class is loaded -- and the scope is any code that can access said stable identifier, eg that which is allowed via the visibility modifiers, although reflection could also be considered.

However, variables are not GC'ed -- objects are, so explicitly/manually setting the variable to "null" or a "dummy object" when it's not being used may -- if there are no other references to the object that the variable used to refer to -- make said object eligible for reclamation.

However, it is best to avoid static values, if at all possible as this can also help with implicit object lifetime control.

Happy coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM