Weak hashmap with weak references to the values?
Posted
by
Razor Storm
on Stack Overflow
See other posts from Stack Overflow
or by Razor Storm
Published on 2012-12-15T03:36:13Z
Indexed on
2012/12/15
5:04 UTC
Read the original article
Hit count: 250
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.
© Stack Overflow or respective owner