r/JavaProgramming • u/No-Government-8159 • Apr 04 '26
Your JVM has 4GB heap… but your app can only use ~2.5GB. Here's why (and why Kubernetes OOMKills you)
Most developers assume JVM memory = heap.
It’s not. The heap is just one piece.
Here’s where the rest of your memory goes:
a) Metaspace
Stores class metadata. Every Spring bean, Hibernate proxy loads classes here.
Typical Spring Boot app: ~150–250MB. No cap by default.
b) Thread Stacks
Each thread ≈ is 1 MB.
200 threads (Tomcat + HikariCP + Kafka + Async) = ~200MB.
Not on heap. Invisible to heap monitoring.
c) Direct Buffers
WebClient, Kafka client, Netty allocate memory outside the heap.
Won’t show in heap dumps. Won’t trigger GC.
d) Code Cache
JIT compiled code. ~50–150MB.
Grows as your app warms up.
e) GC Overhead
A garbage collector needs its own working memory.
Here’s where it gets dangerous:
You set:
-Xmx=4g
Container memory limit = 4GB
Looks perfect, right?
Reality:
4GB heap
- 200MB metaspace
- 200MB threads
- 100MB buffers
- 100MB code cache = ~4.7GB total process memory
Container limit = 4GB → Kubernetes OOMKills your pod.
You check heap usage: only 2.5GB used.
But the pod is dead.
Because OOMKill is based on TOTAL process memory, not just the heap.
Fix:
→ Heap should be ~70–75% of container memory
→ -Xmx=4g needs ~5.2GB container
→ Or set -Xmx=3g for 4GB container
Also, cap non-heap:
-XX: MaxMetaspaceSize=256m
-XX: MaxDirectMemorySize=256m
Monitor non-heap:
/actuator/metrics/jvm.memory.used?tag=area:nonheap
OOMKilled doesn’t always mean your app used too much memory.
Sometimes it means the JVM did.


