OutOfMemoryError (OOM) xảy ra khi JVM không cấp phát được bộ nhớ — heap đầy, GC không giải phóng đủ.
Các loại OOM thường gặp:
- Java heap space — heap đầy. Phổ biến nhất.
- GC overhead limit exceeded — GC chạy >98% thời gian mà chỉ giải phóng được <2%.
- Metaspace — class metadata đầy (Java 8+, thay PermGen).
- Direct buffer memory — direct ByteBuffer (NIO) tràn.
- unable to create new native thread — quá nhiều thread, hết stack.
Nguyên nhân:
- Memory leak (reference giữ object không dùng).
- Data structure phình mãi (cache không evict).
- Heap size không đủ cho workload.
Phòng tránh:
1. Tăng heap nếu workload thật sự lớn: -Xmx2048m.
2. Fix leak: tìm reference thừa (static collection, listener không unregister, ThreadLocal).
3. Cache có eviction policy (Caffeine, LinkedHashMap.removeEldestEntry).
4. Bật heap dump khi OOM để debug: -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dump.
5. Profile với Eclipse MAT, JFR, VisualVM.
OutOfMemoryError (OOM) is thrown when the JVM cannot allocate memory — heap exhausted, GC cannot free enough.
Common OOM variants:
- Java heap space — heap full. Most common.
- GC overhead limit exceeded — GC runs >98% of the time but frees <2%.
- Metaspace — class metadata full (Java 8+, replaced PermGen).
- Direct buffer memory — direct NIO ByteBuffers exhausted.
- unable to create new native thread — too many threads, no stack room.
Causes:
- Memory leaks (references holding unused objects).
- Unbounded data structures (caches with no eviction).
- Insufficient heap for the workload.
Prevention:
1. Increase heap if the workload genuinely needs it: -Xmx2048m.
2. Fix leaks: hunt down extra references (static collections, unregistered listeners, ThreadLocal).
3. Caches need eviction policies (Caffeine, LinkedHashMap.removeEldestEntry).
4. Enable heap dumps on OOM for debugging: -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dump.
5. Profile with Eclipse MAT, JFR, VisualVM.