When resizing large raster images to load the image faster on the server, I sometimes encountered OutOfMemoryErrors. To prevent this, I calculate the required amount of memory and check if it exceeds Runtime.getRuntime (). MaxMemory () before scaling the image.
However, I still encounter OOM errors, although the image should easily be inserted into the heap.
The emulated device (Galaxy SII API 16) gives me a maximum memory of 67108864 bytes using the above method.
In the following fragment, the heap size is 43975 K and only <15K of this memory is used. For my distribution of ~ 31K, the heap should automatically grow to about 45K, which is still not even close to the maximum size of 64 MiB. But, as you can see, instead of expanding the heap, dalvik vm runs out of memory.
10-13 20:35:57.223: D/dalvikvm(1201): GC_FOR_ALLOC freed 505K, 67% free 14692K/43975K, paused 31ms, total 31ms 10-13 20:35:57.223: I/dalvikvm-heap(1201): Forcing collection of SoftReferences for 31961100-byte allocation 10-13 20:35:57.251: D/dalvikvm(1201): GC_BEFORE_OOM freed 2K, 67% free 14689K/43975K, paused 29ms, total 29ms 10-13 20:35:57.251: E/dalvikvm-heap(1201): Out of memory on a 31961100-byte allocation.
I wonder if this could happen on a real device or if it could be a genymotion bug.
Is heap a guarantee of expanding to maxMemory ()? JavaDoc for Runtime.getRuntime (). FreeMemory () says that it can βexpandβ, whatever that means.
I just need a real way to calculate the amount of memory that I can use, here is how I did it, please correct me if I am wrong:
long maxMemory = Runtime.getRuntime().maxMemory(); long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long availableMemory = maxMemory - usedMemory;
This call raises an OutOfMemoryError: