Reputation: 50412
For a few months now I have been testing my skills with AndEngine framework to develop games for Android.
Now I'm facing a confusing issue, in our project, we hold all TextureAtlas (i.e the textures) of an activity in a static HashMap in this activity. Could this generate some memory leak issue or unpleasant stuff like that ? I've heard lots of contradictory things of static variables in Android so I'm not sure what to think about that.
Note that screen rotation is blocked, so it's at least one trap less.
Thanks in advance !
Upvotes: 0
Views: 710
Reputation: 3322
static variables are bad when there is a back reference to the Activity instance. Because activities recreated several times in the life-cycle of the use of an app (for example when you switch your phone).
For example, the following code is safe:
private static Long mMyLong;
But this one is not safe :
private static Context mContext;
Be careful sometimes, there are some non obvious back references.
To avoid this kind of trouble you should store your static HashMap in your application class (you can find here my other post about application class creation https://stackoverflow.com/a/13994622/1789730). So your hashmap will be created once regardless of your activities lifecycle. Besides, you will gain in performance. To be really sur to not keep any reference, you can set to null the hashmap and its content in YourActivity.onDestroy() and recreate it in YourActivity.onCreate().
You can make the following experience to be sur if hashmap keeps any death references. Put the hashmap in the application class like said above. Flip your phone to portrait/landscape to recreate your activity. So if your activity crashes by using the hashmap objects, that means it keeps references to your activity.
Upvotes: 1
Reputation: 1007296
Could this generate some memory leak issue or unpleasant stuff like that ?
Static data members in Java, by definition, are memory leaks. Those objects, and anything they reference, cannot be garbage collected, at least until the static reference to them is removed.
Whether this is a problem is another matter. Leaking a four-byte integer is not going to be an issue, for example. You can use DDMS to generate a heap dump and use MAT to examine it, to see "for realz" how much memory your static HashMap
of TextureAtlas
is.
For a static collection like a HashMap
, the key will be to make sure that you are removing entries that you no longer need. Memory leaks become a problem when collections grow and grow and grow, because you keep adding things to them and never remove anything. Depending on your situation, a WeakHashMap
(where the keys are held weakly, allowing the map entry to go away when nothing else is using your key) might be a better solution.
Upvotes: 2