01: jvisualvm tutorial to sample Java heap memory

Java does not have a sizeof operator like C++ does. Java uses automatic memory management known as the Garbage Collection, hence it is not that important to evaluate size of various objects. But, for the purpose of learning & fixing any potential memory issues, I have used “jvisualvm”, which is a very handy & free profiling tool that gets shipped with the JDK. This compliments Java primitives & objects – memory consumption interview Q&A

Step 1: Java code to “sample with jvisualvm”

Never ending while loop is used so that the application stay alive to sample the Java memory to see how much memory does “MyWrapper” object occupy. Run the below code from your IDE or command-line.

Step 2: Start jvisualvm

Run the above code as a stand-alone Java application:

1) jps will give the process id of the running JVM process.
2) jvisualvm will start the profiler that is shipped with JDK.

1208 is the pid (i.e process id) of the JVM in which “ObjectSize” is running.

Step 3: jvisualvm GUI opens up as shown below

VisualVM

VisualVM

You can see ObjectSize with pid 1208.

Step 4: jvisualvm tabs

Double click on “ObjectSize with pid 1208.” You will get the following screen, and select the “Sampler” tab.

jvisualvm sampler

jvisualvm sampler

Step 5: jvisualvm memory sampling

Click on the “memory” button,

jvisualvm histogram

jvisualvm histogram

Filter “MyWrapper” by typing it at the bottom

MyWrapper Object on the JVM heap

MyWrapper Object on the JVM heap

Step 6: Why 16 bytes when primitive int data is only 4 bytes?

The Object metadata (aka header information) consumes memory in the heap as described below

1) Class information: 32 bits = 4 bytes.
2) Flags: array or not, hashCode, etc : 32 bits = 4 bytes.
3) Lock information: synchronization 32 bits = 4 bytes.

int number = 32 bits = 4 bytes.

So, total 12 bytes of meta data + 4 bytes of data = 16 bytes.

How about an array that can hold 10 MyWrapper objects

How much memory does the above MyWrapper[ ] take?

Follow the same steps as above.

MyWrapper[ ] heap histogram

MyWrapper[ ] heap histogram

1) The “MyWrapper” object takes “16 bytes” as before

2) The array MyWrapper [ ] takes 4 bytes * 10 = 40 bytes for 10 elements.

The remaining 16 bytes are for the Object meta data (aka array header information).

1) Class information: 32 bits = 4 bytes.
2) Flags: array or not, hashCode, etc: 32 bits = 4 bytes.
3) Lock information: synchronization: 32 bits = 4 bytes.
4) Size of the array 32 bits = 4 bytes.


Categories Menu - Q&As, FAQs & Tutorials

Top