ClassLoadingMXBean exposes the current loaded-class count and lifetime loaded and unloaded totals. Those counters describe class activity, not why a class loader remains reachable.
Java ClassLoadingMXBean: separate live classes from lifetime totals
Operational contract
The sampler reads all three counters without changing verbose loading settings. Because the bean is queried three times, the tuple is a nearby set of observations rather than an atomic snapshot. A rising current count can be expected during startup or plugin loading. A lifetime total only increases and must not be graphed as if it represented current retention. If current count continues rising after equivalent load cycles, inspect loader references and heap evidence; the counters alone cannot identify the retaining object.
Failure case
A service installs 47 rule bundles. Its total loaded count rises even after some bundles unload, because it is a lifetime counter. The current count is the more relevant trend for possible accumulation, but a change in runtime libraries could also alter that trend. The caller tags samples with deployment version and bundle activity before diagnosing a leak.
Java code
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
public class LoadedClassSample {
public record Counts(int current, long loadedSinceStart, long unloadedSinceStart) {}
public static Counts capture() {
ClassLoadingMXBean classes = ManagementFactory.getClassLoadingMXBean();
return new Counts(classes.getLoadedClassCount(),
classes.getTotalLoadedClassCount(), classes.getUnloadedClassCount());
}
}Performance and ownership cost
Reading three counters is O(1) API work and memory. Keeping a bounded history of samples costs O(S) space for S samples. The investigation triggered by a suspicious trend may need a heap dump, which is far more expensive and sensitive.
Common Mistakes
- Do not call a lifetime loaded total the number of live classes.
- Do not infer a class-loader leak from one rising sample.
- Do not enable verbose class loading inside a passive sampler.
Connected lessons
- Java modules: readability, exports and reflection boundaries
- Java JVM memory: stack frames, heap objects, and reachability
- 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 MemoryMXBean: read used, committed, and an optional maximum
- Java file channels and JVM observations quiz
- Advanced Java
