简体   繁体   中英

How can I get the occupied space by a java object in the memory heap?

How much space does an object takes from the memory heap? How can this be done?

This is far more complex than just using free memory computations (which don't take into consideration garbage collections and new allocations by other threads). Take a look at:

http://www.javaspecialists.eu/archive/Issue142.html

This is advanced stuff, however.

--EDIT--

The solution above finds the deep size of an object (using a stack to traverse the reference network, a collection of visited references, and of course instrumentation).

However, getting the shallow size of an object is simpler, and can be achieved by java 1.5 instrumentation without extra work (see Instrumentation.getObjectSize() ).

The amount of memory taken by an object varies from one JVM implementation to the next and sometimes from one platform to the next.

You can estimate the amount by counting up the number and size of primitive types and object references declared as instance variables of the object's class.

For example:

public class Monkey {
  int arms;
  Animal parent;
}

..has 1 object reference and 1 int primitive, which on a 32-bit architecture will take up approximately 8 bytes per instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM