You will get an OutOfMemoryError when there is no single continuous heap block that matches your requested size. This can happen when there is still a lot of free space on the heap, but all this is a series of smaller uncomfortable blocks.
For example, pretend we had a 3K heap, and we make three 1K distributions: A, B, and C. Right now, our heap is exhausted since we used all 3K of our 3K heap.
Now A receives the collected garabez. Our heap has 1K free space in a 1K block. If we try to allocate a 1.5K block, we get an OutOfMemoryError because there is not enough space for the heap.
Now C gets garbage collection. A and C, however, are incompatible - B is between them. Memory A and C cannot be combined into one block. Therefore, although we have 2 Kbytes of heap space, we will still fail with OutOfMemoryError on request for a 1.5K request, because there is no single contiguous block of memory that matches the desired size. Only if B also receives garbage collection, our blocks will be merged back into a 3K heap, and at this point we can provide 1.5K allocation.
That's why prudently recycling your allocated memory is important for Android when working with large images or other large blocks (for example, use inBitmap in BitmapOptions ).
source share