It seams that Dalvik’s garbage collector doesn’t respect SoftReferences and removes them as soon as possible, just like WeakReferences. I’m not 100% sure yet, but despite the fact that there is still ~3MB of free memory my SoftReferences get cleared after I see “GC freed bla-bla-bla bytes” in LogCat.
Also, I saw a comment by Mark Murphy here:
Except that it doesn’t work on
Android, at least in the 1.5
timeframe. I have no idea if the GC
SoftReference bugs have been fixed.
SoftReferences get GC’d too soon with
this bug.
Is it true? Are SoftReferences not respected?
How to workaround this?
After not receiving an answer I decided to make my own study. I’ve made a simple test to exercise the GC against SoftReferences.
The idea is that I make few runs of the same code increasing stress on SoftReferences each time (by running more GC passes).
Results are pretty interesting: All runs pass just fine except for one!
These test results are stable. I’ve tried many times and every time it is the same. So I believe it is indeed a bug in garbage collector.
CONCLUSION
So, what we learn out of this… Using SoftReferences in your code is pointless for Android 1.5-1.6 devices. For these devices you will not get the behavior you expect. I didn’t try for 2.1, however.