Static references are cleared--does Android unload classes at runtime if unused?

后端 未结 4 811
眼角桃花
眼角桃花 2020-12-02 19:05

I have a question specific to how the classloading / garbage collection works in Android. We have stumbled upon this issue a few times now, and as far as I can tell, Android

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 19:35

    I have never in my life seen a static data member declared volatile. I'm not even sure what that means.

    Static data members will exist until the process is terminated or until you get rid of them (e.g., null out the static reference). The process may be terminated once all activities and services are proactively closed by the user (e.g., BACK button) and your code (e.g., stopService()). The process may be terminated even with live components if Android is desperately short on RAM, but this is rather unusual. The process may be terminated with a live service if Android thinks that your service has been in the background too long, though it may restart that service depending on your return value from onStartCommand().

    Classes are not unloaded, period, short of the process being terminated.

    To address the other of @sergui's points, activities may be destroyed, with instance state stored (albeit in RAM, not "fixed storage"), to free up RAM. Android will tend to do this before terminating active processes, though if it destroys the last activity for a process and there are no running services, that process will be a prime candidate for termination.

    The only thing significantly strange about your implementation is your use of volatile.

提交回复
热议问题