Search code examples
androidmemoryallocation

OutOfMemory when allocating int array < free memory


In my android app I'm allocating a large int array. This sometimes gives me an OutOfMemory error, when I think there should be sufficient memory. This is an example of what I get:

// always this value
ActivityManager.some_instance.getMemoryClass() = 128 Mb

// always this value
Runtime.getRuntime().maxMemory()/(1024*1024) = 128 Mb

// example value
Runtime.getRuntime().freeMemory()/(1024*1024) = 81 Mb

// example value, can also be bigger than freeMemory()
arrayLengthToAllocate*4/(1024*1024) = 47 Mb 

To be clear, I get the OutOfMemory error for situations where the last value is larger or smaller than freeMemory().

Why do I get the error? Is the heap size not increased when the allocation is performed? The memory use of the app just before trying to allocate is about 8 Mb, so that cannot be the problem.

PS. Other approaches than using an int[] of what this app is doing are not possible.


Solution

  • I figured out that the problem is heap fragmentation. Defragmentation has limits such that there are simply not enough free consecutive bytes in the heap to fit the single large array. I restructered the data into a two-dimensional array which solves the problem as each row has its own location in the heap. Downside is that retrieving the data from the array is slightly slower.