Creation of Java objects

Source: Internet
Author: User

A long time to learn Java, it is time for a wave of deep thinking. For example: How objects are created and used in the JVM. This article mainly explains the new object creation process. To get a deeper understanding of the recommendations, take a serious look at the "in-depth understanding of Java Virtual machine" Zhou Zhiming wrote.

First think about it: what does the person P = new person () say? Nonsense, it must be the creation of a new object, so how did the JVM help you create it? Where did you create it? How to allocate memory on the heap? How do you find the corresponding object according to the variable? With these questions, keep looking down:

First, find the class that can generate the object

The object is not the Sun monkey, the stone jumps out. You new object, always find the class that can generate this object. So this is what the JVM does:

Virtual opportunity to a new directive, first checks whether the parameters of this directive can be located in the constant pool of a class's symbolic references (these will be recorded in the constant pool of objects that contain your new object), and check whether the class that the symbol reference represents has been loaded, parsed, and initialized. If not, you must first perform the appropriate class loading process, please see my next blog post.

Second, the allocation of memory on the heap

There are classes that can produce objects, and here's what you need to create on the heap, first of all, it needs to be clear that the size of the object is already determined, which is calculated when the class is loaded, including how the stack frame size on the stack is determined, You just need to find a place on the heap that can hold such a large area. So how do we find this area? Find a piece of work? Or is there another way to distribute it?

Two ways to allocate memory:

    1. pointer collisions: assume that the memory in the Java heap is absolutely regular, that all used memory is on one side, that the free memory is on the other side (this is the copy algorithm in the GC), and that a pointer is placed in the middle of the boundary point indicator, The allocated memory simply moves that pointer over the free space to a distance equal to the size of the object, which is called a "pointer collision" (Bump the Pointer).
    2. Idle list: if the memory in the Java heap is not regular, the memory used and the Idle memory are interleaved (this is the markup-cleanup algorithm in the GC), then there is no way to simply do a pointer collision, the virtual machine must maintain a list of which memory blocks are available, how much , a large enough space is found in the list to be allocated to the object instance, and the records on the list are updated, which is called the free list.

So how do the two allocation algorithms actually work?
The choice of which allocation method is determined by whether the Java heap is structured or not, and whether the Java heap is structured or not, is determined by whether the garbage collector in use has a compression collation function. Thus, when using collectors with compact processes such as serial and parnew, the allocation algorithm used by the system is a pointer collision, while the use of CMS, a collector based on the mark-sweep algorithm, usually takes a free list.

Hotspot takes the G1 garbage collector, which has the function of compressing and sorting, and the allocation algorithm used by the system is a pointer collision.

I don't know if you found out. This two memory allocation method seems to apply only to a single thread, what if there are multiple threads allocating memory to multiple objects at the same time? After all, multi-threading is sure to have a competitive problem. No problem, the following two ways to solve the multi-threaded allocation of memory:

    1. CAs synchronous processing: to solve the problem of mutual exclusion is definitely synchronous, and solve the synchronization problem is bound to lock processing. So, in fact, the virtual machine with CAS (Compareandset, optimistic lock) with the failure to retry the way to ensure the atomicity of the update operation.
    2. Local thread allocation buffering: The memory allocation action is divided into different spaces by thread, that is, each thread allocates a small chunk of memory in the Java heap, called the local thread allocation buffer (thread local Allocation buffer,tlab). Which thread allocates memory is allocated on the tlab of which thread, and only when Tlab runs out and assigns a new Tlab, does it require a synchronous lock. If the virtual machine uses Tlab, it can be set by the-xx:+/-usetlab parameter.

Third, the memory layout of the object

The house (memory) is there, so how do you put your object in it? Copy Certainly not, you have to put logical, organized, after all, we are engineering students, can not put too casually, too art.

First, the virtual machine needs to initialize the allocated memory space to a value of 0 (excluding object headers), and if you use Tlab, this process can also be done in advance to Tlab allocation. This step explains why 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 the field. (I personally think: the memory space is initialized to 0 values, but also to empty the original memory data, to hold the existing data this role).

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 : Object header includes two pieces of information

      • The first part stores the runtime data of the object itself, such as the hash code (HASHCODE), the GC generational age, the lock status flag, the thread-held lock, the biased thread ID, the biased timestamp, and so on.
      • The other part is the type pointer. The virtual machine uses this pointer to determine which class the object is an instance of, and the type pointer points to the class corresponding to the method area.
    • instance Data : Valid information that the object is actually stored

      This part of the storage order is affected by the virtual machine Assignment policy parameters (Fieldsallocationstyle) and the order in which the fields are defined in the Java source code. The default allocation policy for the hotspot virtual machine is longs/doubles, INTs, Shorts/chars, Bytes/booleans, oops (ordinary objectpointers), as can be seen from the allocation policy. Fields of the same width are always assigned together. It mainly includes the member variables, which are stored in the method area.

    • Snap To fill

      Because the automatic memory management system of the Hotspot VM requires that the object start address must be an integer multiple of 8 bytes, when the object instance data part is not aligned, it needs to be filled by aligning the padding.

Iv. Initialization of objects

It's all about the JVM, backstage, the default, this section is about initializing the process from the code.

Currently, the object has been basically created, but the member variable is just the default initialization, how to display the initialization values, constructors, member variables, how the code blocks are initialized hungry, what is the order?

To illustrate:

/**Parent Class*/ Public classFather {Private Static intb = 1; Static{System.out.println ("Static initialization block of parent class"); } {System.out.println ("Parent class initialization Block"); }     PublicFather () {System.out.println ("called the parent class without a parameter constructor"); }     PublicFather (intb) { This. B =b; System.out.println ("Call the parameter constructor of the parent class"); }}/**sub-class*/ Public classSonextendsFather {Private Static intA =1; Static{System.out.println ("Subclass Static Initialization Block"); } {System.out.println ("Subclass Initialization Block"); }         PublicSon () {System.out.println ("Constructor of the calling child class"); }     PublicSon (inta) {         This. a=A; System.out.println ("Call the constructor of a subclass"); }} Public classTest { Public Static voidMain (string[] args) {son son=NewSon (); }} 

To print a statement:

static initialization block of parent class

Subclass Static Initialization Block

Parent class Initialization Block

Called the parent class parameterless constructor

Subclass Initialization Block

Constructors that call subclasses

V. Access and positioning of objects

How the object is accessed depends on the virtual machine implementation. There are two ways to access the current mainstream, using a handle and a direct pointer.

    • Handle Access:

In the Java heap, a piece of memory will be partitioned as a handle pool, where the handle address of the object is stored in the reference, and the handle contains the specific address information of the object instance data and the type data.

    • Direct pointer mode:

The object address is stored directly in the reference.

The difference between the two ways:

    1. The biggest benefit of using a handle to access is that the reference variable stores a stable handle address that changes the strength data pointer in the handle when the object is moved (which is a trivial behavior when the object is being garbage collected), but the address that the reference variable points to does not change.
    2. The greatest benefit of using direct pointer access is faster, saving time spent on pointer positioning, but changing the address of the reference variable when the object is moved.

Virtual machine hotspot, which is the second way to access objects, but from the overall scope of software development, various languages and frameworks use handles to access the situation is very common.

Here are the points of knowledge:

When class loads, the method information is stored in memory, called the method area, and is not stored in the heap with the object as you create it. If the instance method also increases with the instance increase, then the memory consumption is too large, in order to achieve a common memory, Java is based on the This keyword, such as: Instance1.instancemethod (); Instance2.instancemethod (); When passed to an object parameter, the Java compiler automatically adds a This parameter, which means that the object reference is passed, although the two objects share a method, but the data produced in their method is private, because the parameter is passed in to the entry in the call stack. , and each object has a different call stack, so it's not confusing. In fact, when each non-static method is called, the Java compiler will automatically add the current call to this method object's parameters, and sometimes in one method call another method, you can not precede the this, because the object parameter to be passed is the object that is currently executing this method.

Summary of the object creation process:

Person p = new person ()

1, because to create the person class object, the Java Virtual Machine (JVM) first to find the Person.class file, if any, load it into memory.
2, no words to load the class, the type information (including static variables, methods, etc.) loaded into the method area.
3. Execute the static code block in this class.
4. Only then do the heap memory space open, and assign the first address to the object.
5. Establish the member properties of the object in heap memory and initialize it (default initialization before display initialization).
6, the initialization of the construction code block.
7. The constructor of the object is initialized.
8. Assign the address (reference) in the heap memory to the P variable in the stack memory.

Reference documents:

Specific procedures for creating Java objects

The whole process of creating objects in the Java heap

Creation of Java objects

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.