The example in this article describes how to calculate (or estimate) the amount of memory occupied by a Java object. Share it with everyone for your reference. The specific analysis is as follows:
Usually, we talk about heap memory usage in the context of "general cases". The following two situations are not included:
In some cases, the JVM does not put the Object into the heap at all. For example: In principle, a small thread-local object exists on the stack, not in the heap.
The amount of memory occupied by an Object depends on the current state of the Object. For example: whether the Object's synchronization lock is in effect, or whether the Object is being recycled.
Let’s first take a look at what a single Object looks like in the heap.
In the heap, each object consists of four fields (A, B, C and D). Let's explain each one below:
A: Object header, which occupies very few bytes and expresses information about the current status of the Object.
B: The space occupied by basic type fields (native fields refer to int, boolean, short, etc.)
C: The space occupied by reference type fields (reference type fields refer to references to other objects, each reference occupies 4 bytes)
D: Space occupied by filler (what is filler will be explained later)
Below we explain A, B, C and D one by one
A: Object header
In memory, the total space occupied by each object not only includes the space required for variables declared within the object, but also includes some additional information, such as object headers and fillers. The function of the "object header" is to record the instance name, ID and instance status of an object (for example, whether the current instance is "reachable", or the status of the current lock, etc.).
In the current JVM version (Hotspot), the number of bytes occupied by the "object header" is as follows:
An ordinary object, occupying 8 bytes
Array, occupies 12 bytes, including 8 bytes + 4 bytes of ordinary objects (array length)
B: basic type
boolean and byte occupy 1 byte, char and short occupy 2 bytes, int and float occupy 4 bytes, long and double occupy 8 bytes
C: reference type
Each reference type occupies 4 bytes
D: filler
In Hotspot, the total space occupied by each object is calculated as a multiple of 8. When the total space occupied by the object (object header + declared variables) is less than a multiple of 8, it will be automatically filled in. However, these filled spaces can be called "fillers". Let’s look at a specific example:
An empty object (without any variables declared) occupies 8 bytes --> the object header occupies 8 bytes
A class that declares only one boolean type variable takes up 16 bytes --> object header (8 bytes) + boolean (1 bytes) + filler (7 bytes)
A class that declares 8 boolean type variables takes up 16 bytes --> object header (8 bytes) + boolean (1 bytes) * 8
The above examples will help us deepen our understanding of Java programming.