I need to programmatically find out exactly how much memory a given Java Object is occupying including the memory occupied by the objects that it is referencing.
I can generate a memory heap dump and analyse the results using a tool. However it takes a considerable amount of time to generate a heap dump and for such a tool to read the dump to generate reports. Given the fact that I will probably need to do this several times, my work would be a lot more agile if I could throw in some code in my project that would give me this value ‘runtime’.
How could I best achieve this?
ps: Specifically I have a collection of objects of type javax.xml.transform.Templates
You will need to use reflection for that. The resulting piece of code is too complicated for me to post here (although it will soon be available as part of a GPL toolkit I am building), but the main idea is:
You need to treat arrays separately (8 bytes of header, 4 bytes of length field, 4*length bytes of table, plus whatever the objects inside are using). You need to process other types of objects iterating through the fields (and it’s parents fields) using reflection.
You also need to keep a set of ‘seen’ objects during the recursion, so as not to count multiple times objects referenced in several places.