I am getting a OutOfMemoryError java heap exception when just allocating and deallocating a byte array, even though there is enough free memory for the allocation. There is a short log below. I know from running on a different JVM, that the problem is due to fragmented memory and that the largest free block is only about 6MB. I thought that the java (oracle) JVM should take care of fragmented memory.

This is my test:

  • Set up the java JVM with params -Xms10M -Xmx10M
  • I allocate a byte array of say 90percent of the JVM Memory.
  • Set this byte array then to null, then try to re-allocate the byte array of 90percent of the JVM memory.
  • We see from the logs that JVM memory has reset to the full amount, yet we cant allocate the same amount of memory.
  • Hence the memory must be fragmented?

Here are my details:

Total Free Memory: 9881728  
Attempting to Allocate Array of size: 6917209  
Freeing Allocated Array of size: 6917209  
Total Free Memory: 9881728  
Attempting to Allocate Array of size: 6917209  
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

The other JVM that I am running is CEE-J by Skelmir, I am running on a low memory device so I cannot set the MaxPermSize. It is interesting that the java heap is split into different areas, can these areas change size after garbage collection ?I have run another tests where I, First create a byte array for about 95 percent of the memory, then release the array again, then I create a load of arrays of objects which contain hashmaps, each with one entry, i clear the array and maps, then reallocate the same arrays again.

I check the memory each time i allocate and free. After doing this say 10 times, i free the memory for the last time, Then I check the memory, see that I have the full JVM allocation, I then try to allocate the 95% of the JVM allocation again and get the same JVM out

Edit
Report