Java: OutOfMemoryError and freeMemory () exception

I have the following test program:

public static void main(String[] args)
{       
    HashMap<Integer, String> hm = new HashMap<Integer,String>(); 
    int i = 1;  
    while(true)
    {
        hm.put(i, "blah");
        i++;
        System.out.println("############"); 
        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 following 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(Test.java:14)

Why am I getting an OutOfMemoryError exception, although the freeMemory () method returns that there is more free memory ??? If there is a way to use all freeMemory ()?

+5
source share
4 answers
  • Runtime.freeMemory () javadoc says it returns"an approximation to the total amount of memory currently available for future allocated objects"

  • , . HashMap , . . , JVM, .

+4

HashMap , . , 300 + K , , -.

void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }
    // ***possible big allocation here***
    Entry[] newTable = new Entry[newCapacity];
    transfer(newTable);
    table = newTable;
    threshold = (int)(newCapacity * loadFactor);
}

( ) Java. , , , , , , . , , . .

+4

, HashMap . , .

+1

, JVM.

0