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

后端 未结 4 818
眼角桃花
眼角桃花 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:15

    Both you (@Matthias) and Mark Murphy (@CommonsWare) are correct in what you say, but the gist seems lost. (The use of volatile is correct and classes are not unloaded.)

    The crux of the question is where initialize is called from.

    Here is what I think is happening:

    • You are calling initialize from an Activity *
    • Android needs more memory, kills the whole Process
    • Android restarts the Application and the top Activity
    • You call getInstance which will return null, as initialize was not called

    Correct me if I'm wrong.


    Update:
    My assumption – that initialize is called from an Activity * – seems to have been wrong in this case. However, I'll leave this answer up because that scenario is a common source of bugs.

提交回复
热议问题