Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to measure memory usage?

843798Aug 1 2001 — edited Aug 2 2001
Hi all!

Is there any more sophisticated way of getting the memory requirements of objects at run-time?

Currently I'm using Runtime.totalMemory()-Runtime.freeMemory() to estimate the memory usage before and after loading the object in question. The difference should be the memory used by the object. I also call upon Runtime.gc() to make sure that the garbage collector is run before each of the measurements. Unfortunately Java doesn't guarantee that the garbage collector is really run and that all unused objects are removed from memory even if it is run.

Although this method gives you a rough indication of memory usage (at least for very big objets), I would like to have something more precise (and repeatable). Using the method above on two big objects created in different order leads to different results.

mneumi

Comments

843798
The is no guarantee how much, when or why the VM allocates and/or frees memory. In some cases, the VM might reserve memory as 'used' even though the objects occupying that memory have been freed. The only real metric is to go through by hand and calculate the size. freeMemory() is really only good for getting a general idea of resource usage.
843798
But how can you measure the memory usage by hand? Java isn't very helpful for this. You can have a educated guess about the size of the basic types, but in the end you're guaranteed nothing. And for non trivial object types the things become much harder. The only way to work out the size of a complex structure I found so far was to have a big array full of these objects and use the method I have described above to measure the total memory usage.
1 - 2
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Aug 30 2001
Added on Aug 1 2001
2 comments
205 views