Anatomia d’un objecte JavaAuthor: Joaquim Perez Noguer | Filed under: Ciència i tecnologia
Com guarda el Java els objectes en memòria? T’ho explica From Java code to Java heap
When your Java code uses the new operator to create an instance of a Java object, much more data is allocated than you might expect.
For example, it might surprise you to know that the size ratio of an int value to an Integer object — the smallest object that can hold an int value — is typically 1:4. The additional overhead is metadata that the JVM uses to describe the Java object, in this case an Integer.
The amount of object metadata varies by JVM version and vendor, but it typically consists of:
Class : A pointer to the class information, which describes the object type. In the case of a java.lang.Integer object, for example, this is a pointer to the java.lang.Integer class.
Flags : A collection of flags that describe the state of the object, including the hash code for the object if it has one, and the shape of the object (that is, whether or not the object is an array).
Lock : The synchronization information for the object — that is, whether the object is currently synchronized.
The object metadata is then followed by the object data itself, consisting of the fields stored in the object instance. In the case of a java.lang.Integer object, this is a single int.So, when you create an instance of a java.lang.Integer object when running a 32-bit JVM, the layout of the object might look like Figure 2:Figure 2. Example layout of a java.lang.Integer object for a 32-bit Java processExample layout of a java.lang.Integer object for a 32-bit Java processAs Figure 2 shows, 128 bits of data are used to store the 32 bits of data in the int value, because the object metadata uses the rest of those 128 bits.