How do we find the size of all instances of a class in JVM? Interested in a general programmatic solution that can be used as a library and not use jstat
or reference-counting that requires modifying the original source code.
List<ReferenceType> classes = vm.classesByName(klass.getName());
List<ObjectReference> objectReferences = classes.get(0).instances(Long.MAX_VALUE);
Using the code above gets me all the ObjectReference
(s) to the objects of a particular class. Ideally, we should be able to get the object from the object-reference and invoke VM.current().sizeOf(Object obj)
using JOL (https://github.com/openjdk/jol). Once I iterate through all object references, I'll get the total size occupied by objects of the class. However, I found no documentation for obtaining an Object
from its ObjectReference
.
Seems like both Eclipse (https://help.eclipse.org/2022-12/index.jsp) and IntelliJ IDEA (https://www.jetbrains.com/help/idea/analyze-objects-in-the-jvm-heap.html) can get objects and compute 'retained size' for any classes. I wasn't able to discover how these IDEs implement this functionality.