问题
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?
回答1:
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 (e.g., while downloading a large file) or at user request (e.g., 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 (e.g., task killer) occurs.
回答2:
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, e.g. 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.
来源:https://stackoverflow.com/questions/5305994/android-static-variable-scope-and-lifetime