简体   繁体   中英

Size of all instances of a class on JVM

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.

In Java objects are generally allocated on the heap. So without modifying the application, you can take a heap dump and analyze it. There are questions with answers here on SO, such as

But rather than creating the solution from scratch and inside your application you might want to look into Application Performance Monitoring tools that can easily be attached to any application and thus are reusable. Here is a noncomplete list of such tools .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM