Why do I get an OutOfMemoryError when inserting 50,000 objects into HashMap?

前端 未结 10 1954
猫巷女王i
猫巷女王i 2021-02-01 08:12

I am trying to insert about 50,000 objects (and therefore 50,000 keys) into a java.util.HashMap. However, I keep getting an OutOfMemo

10条回答
  •  时光取名叫无心
    2021-02-01 08:40

    You can increase the maximum heap size by passing -Xmx128m (where 128 is the number of megabytes) to java. I can't remember the default size, but it strikes me that it was something rather small.

    You can programmatically check how much memory is available by using the Runtime class.

    // Get current size of heap in bytes
    long heapSize = Runtime.getRuntime().totalMemory();
    
    // Get maximum size of heap in bytes. The heap cannot grow beyond this size.
    // Any attempt will result in an OutOfMemoryException.
    long heapMaxSize = Runtime.getRuntime().maxMemory();
    
    // Get amount of free memory within the heap in bytes. This size will increase
    // after garbage collection and decrease as new objects are created.
    long heapFreeSize = Runtime.getRuntime().freeMemory();
    

    (Example from Java Developers Almanac)

    This is also partially addressed in Frequently Asked Questions About the Java HotSpot VM, and in the Java 6 GC Tuning page.

提交回复
热议问题