In this article, we discuss a question: How to calculate (or, estimate) the amount of memory that a Java object occupies?
In general, we are talking about the premise that heap memory is used in a "general" context. The following two scenarios are not included:
- In some cases, the JVM does not put an object into the heap at all. For example: In principle, a small thread-local object exists in the stack, not in the heap.
- The size of the memory that is occupied by object depends on the current state of object. For example, if the synchronization lock for object is in effect, or if object is being reclaimed.
Let's take a look at what a single object in the heap looks like.
In the heap, each object consists of four domains (A, B, C, and D), which we'll explain one by one:
- A: Object header, takes up very few bytes, and expresses information about the current state of object
- B: Space occupied by the base type field (native domain refers to int, Boolean, short, etc.)
- C: The space occupied by the Reference type field (reference Type field refers to a reference to another object, each reference occupies 4 bytes)
- D: Space occupied by the filler (the following is what the filler is)
Below we explain each of a, B, C and D
A: Object Header
In memory, the total space occupied by each object not only contains the space required for variables declared within the object, but also includes additional information such as object headers and padding. The object header is used to record the instance name, ID, and instance state of an object (for example, whether the current instance is reachable, or the state of the current lock, and so on).
In the current JVM version (Hotspot), the object header occupies the following number of bytes:
- An ordinary object that occupies 8 bytes
- An array that occupies a bytes of 8 bytes + 4 bytes (array length) containing ordinary objects
B: Basic type
Boolean, byte occupies 1 Byte,char, short occupies 2 bytes,int, float occupies 4 bytes,long, double occupies 8 bytes
C: Reference type
Each reference type occupies 4 bytes
D: Filler
In a hotspot, the total space occupied by each object is calculated in multiples of 8, and the object occupies a multiple of the total space (object header + declaration variable) less than 8, and is automatically padded. And, these filled spaces, we can call it "filler." Let's take a look at the specific examples:
- An empty object (without declaring any variables) takes up 8 bytes--> object Header occupies 8 bytes
- A class that only declares a Boolean variable, occupies a bytes-to-Object header (8 bytes) + Boolean (1 bytes) + filler (7 bytes)
- Class with 8 Boolean variables declared, occupied by bytes (8 bytes) + Boolean (1 bytes) * 8
through the above examples, it is more helpful for us to understand. ^_^
Java memory usage-how to calculate the number of bytes consumed by a Java object