is it possible for Android VM to garbage collect s

2019-01-23 17:47发布

问题:

(Title is misleading since garbage collectors collect only objects, but I found this title more straightforward)

Suppose I have an Android application with a static variable named "userid" inside a class called Global (which is null at initialization time).

If I set "userid" variable to some value duing Android application lifecycle, say Global.userid = "myid", is it possible for this variable to become null while Android application is still alive?

In other words, is it possible for Android VM to unload Global class and "kill" this global static variable due to low-memory issue without killing the whole Android application?

I am worried about the situation that userid becomes suddenly null while application is running (due to low memory issue), therefore crashing the whole app.

Edit I was misunderstanding some concepts (between application process vs activities). Thanks for all answers!

回答1:

If I set "userid" variable to some value duing Android application lifecycle, say Global.userid = "myid", is it possible for this variable to become null while Android application is still alive?

If you set it to null yourself, yes.

In other words, is it possible for Android VM to unload Global class and "kill" this global static variable due to low-memory issue without killing the whole Android application?

For normal cases, no.

If you play around with custom classloaders, it is conceivable that there may be scenarios in which classes get unloaded (and hence any static data members on them go poof) -- I seem to recall there was discussion about this scenario, but I forget the conclusion. However, very few apps should be messing around with custom classloaders.

I am worried about the situation that userid becomes suddenly null while application is running (due to low memory issue), therefore crashing the whole app.

That should not happen.

What can happen is that the user is in your app, leaves the app via HOME (or a notification, or an incoming call, or the recent-tasks list, etc.), then later returns to your app via the recent-tasks list. If your process had been terminated during the time it was not in the foreground, your static data member will be null when your activity is started up from the recent-tasks list. Since the activity the user returns to may not necessarily be your launcher activity, your app may behave as though the static data member spontaneously turned null, even though it was because your process had been terminated and restarted.

This is one of several reasons why static data members need to be used very carefully.



回答2:

If you are making the variable static so that you can access it from anywhere in your app without creating a new instance of the class every time I believe this is a good candidate for the Singleton pattern.

String userid = Global.getInstance().userid;