Forum Stats

  • 3,781,640 Users
  • 2,254,533 Discussions


How to measure memory usage?

843798 Member Posts: 24,864
edited Aug 2, 2001 4:56AM in Java Runtime Environment (JRE)
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.



  • 843798
    843798 Member Posts: 24,864
    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
    843798 Member Posts: 24,864
    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.
This discussion has been closed.