Object instantiation in several ways

Java programs create objects in the following ways:

  1. newKeyword creation;
    • Create an object by calling the class constructor with the new keyword;
    • Call the getXXXInstance method of the object (singleton mode);
    • XXXBuilder/XXXFactory.
  2. Reflection, Class newInstance method or Constructor newInstance method;
  3. Using the clone method of class;
  4. Use deserialization;
  5. Third-party library Objenesis.

Object creation Steps

The object creation process is divided into the following steps:

  1. Determine whether the corresponding class of the object has been loaded (three steps of class loading: loading, linking, and initialization);

  2. Allocates memory for objects.

    Calculate the size of the object, and then allocate a chunk of memory in the heap to hold the object. There are two types of memory allocation:

    • When memory is organized, pointer collisions are used. All the used memory is on one side, and all the free memory is on the other, with a pointer in the middle as a pointer to the dividing point. Allocating memory simply moves the pointer to the free side by an equal distance to the size of the object.
    • If the memory is not regular, the VM needs to maintain a list and use the free list to allocate memory. In this case, used memory and unused memory are interlocked, the virtual machine maintains a list of which memory blocks are available, finds a large enough space from the list to allocate to object instances at allocation time, and updates the free list.

    The choice of allocation depends on whether the Java heap memory is clean, which in turn depends on whether the garbage collector has compression capabilities.

  3. Handle concurrency security issues. Virtual machines use CAS and TLAB to ensure thread-safety during object creation.

  4. Initialize the allocated space. Once the memory is allocated, the virtual machine initializes all allocated memory space to zero (the default value, excluding object headers).

  5. Set the object header. The object’s owning class (that is, the metadata information of the class), the object’s HashCode, and the object’s GC information, lock information and other data are stored in the object header of the object.

  6. Execute the

    method to initialize. The

    method contains constructors for initializing member variables, executing instantiation blocks, and calling classes:

     public class Test {
        private int a = 111;
        private int b;
        private int c;
    
        {
            b = 222;
        }
    
        public Test(a) {
            c = 333; }}Copy the code

    Use jclasslib to look at its

    method:

Again, the '<init>' method contains initializing member variables, executing instantiation blocks, and calling class constructors.Copy the code

Object memory layout

Objects in heap space contain the following structures internally:

  1. Object.

    The object header contains two pieces of data:

    • Runtime metadata: HashCode, object age, lock status flags, locks held by threads, etc.
    • Type pointer: Points to class metadata to determine the type to which the object belongs.

    If the object is an array, you also record the length of the array.

  2. Instance data.

    That is, the various type attributes defined in a class (both inherited from a parent class and defined by itself). Instance data storage has certain rules: fields of the same width are always assigned together; Variables defined in a parent class appear before subclasses.

  3. Alignment padding: not required, has no special meaning, and serves as a placeholder.

Here is an example to illustrate the memory layout of an object. The following code is available:

public class Customer {
    int id = 100;
    String name;
    Account account;

    {
        name = "Big account";
    }

    public Customer(a) {
        account = new Account();
    }

    public static void main(String[] args) {
        Customer customer = newCustomer(); }}class Account {}Copy the code

After the Customer object is created using the main method, the related memory layout is shown as follows: