Reputation: 34550
I have a bitmap cache in my Android app where the bitmaps are referenced via SoftReference. However the bitmaps are nulled too early. There can be 20 bitmaps max in the cache, if I load more, GC starts to null the SoftReferences. Without SoftReferences, I can have about 110 bitmaps in cache. Isn't SoftReference supposed to null just before OutOfMemoryError would happen?
Upvotes: 1
Views: 439
Reputation: 2289
In my case, Hashmap(bitmap cache) got nulls if I got back from the other Activity. So, I fixed my code like below pseudo-code.
void displayImageFunction() {
if(mImageCacheMap.containsKey(key)) {
Bitmap bitmapToShow = mImageCacheMap.get(url).get();
if(bitmapToShow != null) {
//> Image was cached well
//> Set "bitmapToShow" to UI
return;
}
}
//> Read from file DB(or Web) and...
Bitmap bmp = getBitmap(imageToLoad.url);
//> put it to Hashmap again...
mImageCacheMap.put(key, new SoftReference<Bitmap>(bmp));
//> Set "bmp" to UI
}
I think we should prefare for nulls. Because, we cannot know when GC collects garbage. :)
Upvotes: 0
Reputation: 9910
No, the implication works the other way around:
It is guaranteed that the Java runtime will nullify SoftReferences, if any, before throwing a OutOfMemoryError. However, it does not guarantee that the SoftReference will get nullified only under this condition.
Upvotes: 5