Java GC Tutorials - Herong's Tutorial Examples - v1.11, by Dr. Herong Yang
Java Exception: "java.lang.OutOfMemoryError: Java heap space"
This section provides a tutorial example on how JVM expands the Heap space to allocate more objects and leads to the 'java.lang.OutOfMemoryError: Java heap space' Java exception, if it is not allowed to expand any more.
First, let's use the following simple program, HeapMemoryCrash.java, to observe what will happen when the Heap runs out of memory:
/* HeapMemoryCrash.java * Copyright (c) HerongYang.com. All Rights Reserved. */ class HeapMemoryCrash { public static void main(String[] a) { int max = 1000; Object[] arr = new Object[max]; heapCheck(); for (int n=0; n<max; n++) { arr[n] = new long[10*1024*128]; System.out.println((n+1)+": " +((n+1)*10)+" MB of objects created."); heapCheck(); } } public static void heapCheck() { Runtime rt = Runtime.getRuntime(); rt.gc(); long total = rt.totalMemory(); long free = rt.freeMemory(); long used = total - free; java.io.Console con = System.console(); con.format("Total memory: %s%n",total); con.format(" Free memory: %s%n",free); con.format(" Used memory: %s%n",used); String str = con.readLine("Press ENTER key to continue: "); } }
This program is designed to:
Compile and run with HotSpot JVM from JDK 17:
herong> javac HeapMemoryCrash.java herong> java -Xms20m -Xmx50m HeapMemoryCrash Total memory: 20447232 Free memory: 20188720 Used memory: 258512 Press ENTER key to continue: 1: 10 MB of objects created. Total memory: 26152960 Free memory: 15377464 Used memory: 10775496 Press ENTER key to continue: 2: 20 MB of objects created. Total memory: 50724864 Free memory: 29463808 Used memory: 21261056 Press ENTER key to continue: 3: 30 MB of objects created. Total memory: 50724864 Free memory: 18978032 Used memory: 31746832 Press ENTER key to continue: 4: 40 MB of objects created. Total memory: 50724864 Free memory: 8492256 Used memory: 42232608 Press ENTER key to continue: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at HeapMemoryCrash.main(HeapMemoryCrash.java:10)
The output confirms that:
Table of Contents
►Heap Memory Area and Size Control
►Java Exception: "java.lang.OutOfMemoryError: Java heap space"
Memory Allocation Limits on Windows Systems
OutOfMemoryError Comparison of HotSpot and JRockit
JVM Garbage Collection Logging
Introduction of Garbage Collectors
Serial Collector - "+XX:+UseSerialGC"
Parallel Collector - "+XX:+UseParallelGC"
Concurrent Mark-Sweep (CMS) Collector - "+XX:+UseConcMarkSweepGC"
Garbage First (G1) Collector - "+XX:+UseG1GC"
The Z Garbage Collector (ZGC) - "+XX:+UseZGC"
Object References and Garbage Collection
Garbage Collection Performance Test Program
Performance Tests on Serial Collector
Performance Tests on Parallel collector
Performance Tests on Concurrent collector
Performance Tests on G1 collector