Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java ClassLoadingMXBean: separate live classes from lifetime totals

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

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.

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

Java
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
jvm management observations
classloading-mxbean-counts
Storage details