Java Object Memory Layout / Anatomy —Deep Size of an Object
Even to the mind of the most experienced Java Developer, the way JVM organizes or allocates memory for an Object may not come intuitively. Memory layout is key.
Join the DZone community and get the full member experience.Join For Free
even to the mind of the most experienced java developer, the way jvm organizes or allocates memory for an object may not come intuitively. this also includes activities like measuring the size of an object.
when we use 'new' to instantiate an object, there is much more data size allocated than is required to just hold the value. for example, if you choose to create java.lang.integer, the actual int value will be only 1:4 parts of the object. the remaining is used to hold the metadata - the metadata includes the following:
1. class: a pointer to the type of the class. in our case, a pointer to the java.lang.integer class.
2. flags: a collection of flags that describe the state of the object, including the hash code of the object and the shape of the object (if it is an array or not)
3. lock: the synchronization information of the object, including if it is synchronized currently.
the object metadata is followed by the actual object data. in this specific case, an int value.
example layout of a
object for a 32-bit java process
i tried to explore all possibilities to measure the object memory usage as per the above understanding of the object allocation. there are many tools, blogs and write-ups on the internet, but all of them provide approximation, which may not be reliably usable. also, the values which may be returned by each of these will not concur across these tools.
the only tool that i came across that seems to be reliable and has the source code public is the java agent for memory measurements [https://github.com/jbellis/jamm]. the author also seems to be the committer for the cassandra project, and it is being used in cassandra - hence, it is a safe bet and should be close to as exact as possible. i went through the source and the logic seems to concur with the memory layout above, also, since it is being used in very important (and widely used) projects, [i skipped trying it out myself]. in all, this should be your safest [reliablity and performance] bet if you want to use it to introduce custom cache measurements, custom object profiling, server profiling or simply memory profiling tools.
[i plan to write my own tool to measure object sizes in java as reliably as possible - using the above understanding of java memory allocation . keep checking this blog to download the source and binary]
Published at DZone with permission of Sumith Puri. See the original article here.
Opinions expressed by DZone contributors are their own.