"In-depth understanding of the JVM": Creation of Java objects, memory layout, access positioning

Source: Internet
Author: User

Creation of Objects

A simple Creation object statement Clazz instance = new Clazz(); consists of a class load check, object allocation memory, concurrency processing, memory space initialization, object setting, execution ini method, and so on.

The main processes are as follows:

1. Class load Check

When the JVM encounters a new directive, it first checks to see if the parameter of the directive can locate the symbolic reference of a class in the constant pool, and checks whether the class represented by the symbol reference has been loaded, parsed, and initialized. If not, you must first perform the appropriate class loading process.

2. Object Allocation Memory

The size of the memory required for an object is fully determined when the class is loaded ( object memory Layout ), and the task of allocating space to an object is equivalent to dividing a size of memory from the Java heap.

There are two ways of allocating memory according to whether the Java heap is structured: (Whether the Java heap is structured by the garbage collector in use or not)

    • Pointer collision (Bump the pointer)
      The memory in the Java heap is regular, all the used memory is on one side, the free memory is on the other side, a pointer is placed in the middle of the point indicator, allocating memory is to move the pointer to the free space beyond the distance of the size of the memory. For example: Serial, parnew and other collectors.
    • Idle lists (free list)
      The memory in the Java heap is not regular, the memory used and the free memory interleaved, there is no way to simply do a pointer collision. The virtual machine must maintain a list of which memory blocks are available, find a large enough space in the list to be allocated to the object instance, and update the records on the list. For example, CMS is a collector based on the mark-sweep algorithm.
3. Concurrent processing

Object creates a very frequent behavior in a virtual machine, even if it only modifies the location where a pointer is pointing, it is not thread-safe in the concurrency scenario, it is possible to allocate memory to object A, the pointer has not yet been modified, and object B uses the original pointer to allocate memory.

    • Synchronous
      The virtual machine uses CAs to match the failure retry to ensure the atomicity of the update operation
    • Local thread allocation buffer (thred locally Allocation buffer, Tlab)
      The actions of memory allocation are divided into different spaces, that is, each thread pre-allocates a small chunk of memory (Tlab) in the Java heap. Which thread allocates memory, on which thread the Tlab is allocated. A sync lock is required only if the Tlab runs out and assigns a new tlab.
4. Initialization of memory space

The memory space that the virtual machine allocates to is initialized to a value of 0 (excluding the object header), and if Tlab is used, the work process can be done in advance to Tlab allocation.

Memory space initialization guarantees that an instance field of an object can be used directly in Java code without assigning an initial value, and the program can access the 0 value corresponding to the data type of those fields.

Note: A member variable of a class can be initialized without being displayed (the Java Virtual machine will automatically initialize it to its default value first). Local variables in a method are not initialized if they are only responsible for receiving the value of an expression, but local variables that participate in other situations, such as operations and direct output, need to be initialized.

5. Object Settings

The virtual machine makes the necessary settings for the object, such as which class the object is an instance of, how to find the metadata information for the class, the object's hash code, the age of the object's GC, and so on. This information is stored in the object's header.

6. Execute init ()

After the above work is done, a new object has been created from the virtual machine's point of view. But from the Java program's point of view, the creation of the object has just begun the Init () method has not been executed, all fields are still zero.

So, in general (as determined by the Invokespecial directive in bytecode), the init () method is followed by the execution of the new instruction, which initializes the object according to the programmer's will, so that a truly usable object is generated.

Object Memory Layout

In a hotspot virtual machine, the layout of objects stored in memory can be divided into 3 areas: Object Header (header), instance data (Instance), and aligned padding (Padding).

Object Header

The object header of a hotspot virtual machine consists of two pieces of information: runtime data and type pointers.

Run-time data

The runtime data used to store the object itself, such as hash code (HASHCODE), GC generational age, lock status flag, thread-held lock, biased thread ID, biased timestamp, and so on.

Type pointer

That is, the object points to its class metadata pointer, which the virtual machine uses to determine which class the object is an instance of.

If the object is a Java array, then there must be a piece of data in the object header that records the length of the array, because the virtual machine can determine the size of the Java object through the metadata information of the ordinary Java object, but the size of the array cannot be determined from the array's metadata.
(Not all virtual machine implementations must keep type pointers on object data, in other words, finding the object's metadata does not necessarily go through the object itself, but can refer to the object's access location)

instance Data

The instance data section is a valid piece of information that the object actually stores, as well as the various types of field content defined in the program code. Whether it's inherited from a parent class or defined in a subclass, it needs to be documented. The default allocation policy for the hotspot virtual machine is longs/doubles, INTs, Shorts/chars, Bytes/booleans, and OOP, as can be seen from the allocation policy, where fields of the same width are always assigned together.

Snap To fill

The hotspot virtual machine requires that the starting address of the object must be an integer multiple of 8 bytes, i.e. the size of the object must be an integer multiple of 8 bytes. The head part of the object is exactly a multiple of 8 bytes (1 time times or twice times), so when the object instance data part is not aligned, it needs to be filled by aligning the padding.

Object Access targeting

Java programs need to manipulate the concrete objects on the heap through reference data on the stack. The way objects are accessed depends on the implementation of the virtual machine, and there are two main ways to access it using both a handle and a direct pointer.

A handle, which can be understood as a pointer to a pointer, maintains a pointer change to an object, and the object's handle itself does not change; A pointer to an object that represents the memory address of the object.

Handle
The Java heap divides a piece of memory into a handle pool, which stores the handle address of the object in the reference, and the handle contains the specific address information of the object instance data and the type data.

Advantage: A stable handle address is stored in the reference, and only the instance data pointers in the handle are changed when the object is moved (garbage collection is a very common behavior), and the reference itself does not need to be modified.

Direct pointer

If you use direct pointer access, then the layout of the Java heap object must consider how to place information about the access type data, whereas the reference stores the object address directly.

Advantage: Faster and saves time overhead for pointer positioning. Because object access is very frequent in Java, this overhead is a significant execution cost. (e.g. hotspot)

Reference
1, Zhou Zhiming, in-depth understanding of Java Virtual machines: JVM advanced features and best practices, mechanical industry Press

"In-depth understanding of the JVM": Creation of Java objects, memory layout, access positioning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.