Java: OutOfMemoryError Exception and freeMemory()


I have the following test program:

public static void main(String[] args)
    HashMap<Integer, String> hm = new HashMap<Integer,String>(); 
    int i = 1;  
        hm.put(i, "blah");
        System.out.println("Max mem: " + Runtime.getRuntime().maxMemory()); 
        System.out.println("Total mem: " + Runtime.getRuntime().totalMemory()); 
        System.out.println("Free mem:" + Runtime.getRuntime().freeMemory());

If I run this program, I get the follwing output:


    Max mem: 8060928

    Total mem: 8060928

    Free mem:334400

    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at java.util.HashMap.addEntry(Unknown Source)
        at java.util.HashMap.put(Unknown Source)
        at Test.main(

Why I get an "OutOfMemoryError" Exception although the method freeMemory() returns that there is more free memory??? If there a way to use all the freeMemory()?


It seems like amount of free memory is not enough to run the JVM.

You will be getting the out of memory exception at the point where the HashMap need to expand it's internal storage. The requirement for this will be greater than the available feel memory.

  1. Runtime.freeMemory() javadoc says that is returns "an approximation to the total amount of memory currently available for future allocated objects"

  2. The way all dynamic structures work is that they allocate memory in chunks. When HashMap is getting full it doesn't allocate extra space for just one more object. It allocates a chunk of some size. I do not know the exact way it works in JVM, but it may try to allocate as much as twice the amount of current memory it uses.

By : pajton

This video can help you solving your question :)
By: admin