MemoryMXBean reports a current heap usage observation. Used, committed, and maximum bytes answer different questions; maximum can be undefined.
Java MemoryMXBean: read used, committed, and an optional maximum
Operational contract
This sampler retains one value object with those three fields. Used includes live objects and objects not yet collected, so one high reading is not evidence of a leak. Committed is storage available to the JVM, while max is a configured or implementation limit and may be -1. Heap does not include every form of process memory. Compare equivalent workload phases across time and use allocation, GC, and retained-object evidence before deciding that growth is pathological. Do not call System.gc merely to make a dashboard number look smaller.
Failure case
A depot processes 47 batches. Heap used rises while a batch is active, then falls after the system reaches its normal idle point. That pattern differs from an idle floor that rises after each equivalent batch. The sampler records raw values; interpretation requires timestamps and workload context supplied by its caller.
Java code
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.util.OptionalLong;
public class HeapUsageSample {
public record Snapshot(long usedBytes, long committedBytes, OptionalLong maxBytes) {}
public static Snapshot capture() {
MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
long maximum = heap.getMax();
return new Snapshot(heap.getUsed(), heap.getCommitted(),
maximum < 0 ? OptionalLong.empty() : OptionalLong.of(maximum));
}
}Performance and ownership cost
Capturing three scalar fields uses O(1) application memory and time relative to heap size. Sampling too frequently can add monitoring overhead, and storing every sample indefinitely creates its own retention problem.
Common Mistakes
- Do not interpret one used-heap value as a leak.
- Do not use -1 maximum as a real byte limit.
- Do not confuse heap usage with total process memory.
Connected lessons
- Java JVM memory: stack frames, heap objects, and reachability
- Java garbage collection: diagnose retention before tuning
- Java heap diagnostics: retained objects, histograms and a controlled dump
- Java ThreadMXBean deadlocks: diagnose platform-thread cycles
- Java ThreadMXBean CPU time: check support and the disabled state
- Java ClassLoadingMXBean: separate live classes from lifetime totals
- Java file channels and JVM observations quiz
- Advanced Java
