How do I keep track when class is loaded and destroyed in jvm? Is there any callback method that is exposed by the jvm?
8 Answers
If you're using a Sun/Oracle JVM, you could use the TraceClassLoading
and TraceClassUnloading
options. Use the following to see what options your JVM supports:
java -XX:+AggressiveOpts -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+PrintFlagsFinal -version
If these options are supported, run your Java application using -XX:+TraceClassLoading -XX:+TraceClassUnloading
. You should see messages like:
[Loaded ... from ...]
[Unloading class ...]

- 15,194
- 6
- 41
- 65
-
`TraceClassLoading` was "expired" in JDK 17 unfortunately: https://chriswhocodes.com/hotspot_options_openjdk8.html?s=TraceClassLoading and the alternative seems to be `-verbose:class` or `-Xlog:class+load -Xlog:class+unload` – Guillaume Aug 22 '22 at 16:29
You can add the command line option -verbose:class
to your Java process, this will
display information about each class loaded.

- 23,135
- 6
- 55
- 69
You can add Java Opts to see which class is loaded via:
java -verbose:class
About destroyed class, I am not sure.

- 9,485
- 42
- 40
From Java 9 onward, you can use -Xlog
. e.g.:
java -Xlog:class+load -Xlog:class+unload ...
This will print entries like:
[0.296s][info][class,load] java.lang.Shutdown source: jrt:/java.base
[0.296s][info][class,load] java.lang.Shutdown$Lock source: jrt:/java.base
You can also use -Xlog:help
to get more information on the option.

- 31,735
- 4
- 76
- 93
If are ok with using JRockit JVM, you can make use of the APIs below, which will give you callback methods when a class is loaded and class is unloaded.
Have a look at JVM class from which we are supposed to use the getClassLibrary()
method.
On the classLibrary object we can register listeners for classloading events which gives the class names etc.

- 1,812
- 13
- 17
You can use static block to detect class loading but you can not detect class unloading. In java all classes loaded through the system classloader will never be unloaded and all classes loaded through other classloaders will be unloaded only when the classloader is unloaded.
static{
//execute when the class will be loaded
}

- 4,223
- 1
- 21
- 24
Do you want this information in your application or do you just want to analyse that from the outside? In the latter case you maybe can use VisualVM for that. Maybe your question is related to this one: Loaded classes in VisualVM.
You can track class's creation in static constructor. And you cannot track it's destruction as far as I'm concerned. Classes are only unloaded when gc collects the classloader which was used to load the classes.
You might also be interested in reading this: another question on classloaders at StackOverflow

- 1
- 1

- 666
- 6
- 11