Java core learning path Level 3 This level · 10 of 19
Medium java java-21

How do you optimize memory usage in a Java application?

The 30 second answer

I measure before changing anything: heap used after garbage collection, plus a heap dump and a class histogram to see what's really taking space. Then I fix leaks like unbounded caches, static maps, listeners that are never removed, and thread locals never cleared. I stream large data instead of loading it all, use leaner data structures, and size the heap from measured live data, including container limits.

Could you say this in an interview?

Measure:

jcmd <pid> GC.class_histogram            # which classes use the most memory
jcmd <pid> GC.heap_dump /tmp/app.hprof   # analyze in Eclipse MAT or VisualVM
-XX:+HeapDumpOnOutOfMemoryError          # capture the moment it fails

Look at retained size and the path to GC roots of the biggest objects.

Common fixes:

  • Leaks: caches without size or TTL limits, static collections, unremoved listeners, ThreadLocal values in pooled threads without remove().
  • Large data: stream from the database or files (pagination, cursors) instead of loading everything with findAll().
  • Overhead: boxed collections like List<Integer> versus int[], oversized initial capacities, duplicate strings (G1 supports -XX:+UseStringDeduplication).
  • Sizing: set -Xmx from live data after a full GC, plus headroom.

[Opinion] In containers prefer -XX:MaxRAMPercentage (for example 70 to 75) over a fixed -Xmx, and leave room for native memory: thread stacks, Metaspace, direct buffers and the code cache.

Alternate interview scenarios

"Your Java application suddenly consumes too much memory. How would you debug it?"

"Suddenly" means I first check what changed, such as a deploy, traffic or the data, and which memory is growing. If heap used after GC keeps rising, it is a heap retention problem and I use the dump-and-histogram steps above. If process or container memory grows while the heap stays flat, the growth is native memory: thread stacks, direct buffers, Metaspace or the code cache. Then I enable Native Memory Tracking with -XX:NativeMemoryTracking=summary and compare jcmd <pid> VM.native_memory snapshots over time. A container that is OOMKilled without a Java OutOfMemoryError usually points to the native side.

"Your Spring Boot service works fine in development but crashes every night at 2am in production. How do you debug it?"

The fixed time is the strongest clue, so I start by looking for what happens at 2am. I check whether it lines up with something scheduled: a @Scheduled job or cron, a batch import, a report, a cache rebuild, a backup or database maintenance, log rotation, or a certificate or token refresh. Then I look at the metrics for the hours before the crash. If heap used after GC keeps rising and never drops, objects are being retained, so I capture a heap dump at OutOfMemoryError (-XX:+HeapDumpOnOutOfMemoryError) and find what holds it. If the heap is flat but the process is killed, that points to native memory or the container limit. If memory looks fine, it may be the connection pool running dry because a job never returns its connections. Leak detection in the pool and try-with-resources point to the code that never closes them. I add an alert that fires early, for example on old-gen usage or pool wait time, and I reproduce the problem by running the 2am job at the same data volume in staging.

Sources (6)
  1. jcmd (GC.heap_dump, GC.class_histogram)docs.oracle.com
  2. Troubleshooting Guide: Memory Leaksdocs.oracle.com
  3. java command optionsdocs.oracle.com
  4. Java 21: Native Memory Trackingdocs.oracle.com
  5. Spring: Task execution and schedulingdocs.spring.io
  6. HikariCP configuration (leakDetectionThreshold)github.com
Previous
Next