Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the number of objects in the heap

Tags:

How can I find the number of live objects on the heap in Java program?

like image 925
java_geek Avatar asked Feb 14 '10 20:02

java_geek


People also ask

Are objects in the heap?

Java objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

How objects are stored in heap?

In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.

Are objects stored in heap memory?

The heap is used for storing objects in memory.


2 Answers

jmap is the standard java utility that you can use to capture heap dumps and statistics. I can't say what protocol is used by jmap to connect to the JVM to get this info, and it's not clear if this information is available to a program running in the JVM directly (though I'm sure the program can query it's JVM through some socket to get this information).

JVM TI is a tool interface used by C code, and it has pretty much full access to the goings on of the JVM, but it is C code and not directly available by the JVM. You could probably write a C lib and then interface with it, but there's nothing out of the box.

There are several JMX MBeans, but I don't think any of them provide an actual object count. You can get memory statistics from these though (these are what JConsole uses). Check out the java.lang.management classes.

If you want some fast (easy to implement, not necessarily a quick result as a jmap takes some time), I'd fork off a run of jmap, and simply read the resulting file.

like image 85
Will Hartung Avatar answered Oct 01 '22 14:10

Will Hartung


The simplest way is to use jmap tool. If you will print objects histogram at the end you'll see total number of instances and also accumulated size of all objects:

jmap -histo <PID> will print whole objects with number of instances and size. The last line will contain total number

Total 2802946 174459656

Second column is total instances count, and last is total bytes.

like image 33
Jakub Kubrynski Avatar answered Oct 01 '22 15:10

Jakub Kubrynski