I am building an android app where each entity has a bitmap that represents its sprite. However, each entity can be be duplicated (there might be 3 copies of entity asdf for example).
One approach is to load all the sprites upfront, and then put the correct sprite in the constructors of the entities.
However, I want to decode the bitmaps lazily, so that the constructors of the entities will decode the bitmaps. The only problem with this is that duplicated entities will load the same bitmap twice, using 2x the memory (Or n times if the entity is created n times).
To fix this, I built a SingularBitmapFactory that will store a decoded Bitmap into a hash, and if the same bitmap is asked for again, will simply return the previously hashed one instead of building a new one. Problem with this, though, is that the factory holds a copy of all bitmaps, and so won't ever get garbage collected.
What's the best way to switch the hashmap to one with weakly referenced values? In otherwords, I want a structure where the values won't be GC'd if any other object holds a reference to it, but as long as no other objects refers it, then it can be GC'd.
Pretty much what you said -- make the Bitmap (object side of the map) a WeakReference instead of a Bitmap. Then you have to add an extra check to see if the reference is still valid before passing it back to your entities. Here is a quick sketch of the general idea.
public class SingularBitmapFactory {
private HashMap <String, WeakReference<Bitmap>> cache = new HashMap<String, WeakReference<Bitmap>>();
public Bitmap getBitmap(String key) {
Bitmap image = null;
WeakReference<Bitmap> ref = cache.get(key);
if(ref != null) {
image = ref.get();
}
if(image == null) {
// Load image here ...
cache.put(key, new WeakReference<Bitmap>(image));
}
return image;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With