This is the 21st day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

1. The birth of an object

When the JVM reads a new instruction from the program counter’s line number, it first looks in the methods section to see if the class has been loaded, parsed, initialized, or loaded first.

Once the class is loaded, it allocates memory in the Java heap. If the memory in the Java heap is very neat, recording the boundary between used and unused areas, then allocating memory simply moves the boundary some distance in the direction of unused memory. This is called “pointer collision”. If the memory is not tidy, the virtual machine needs to maintain a separate list of what memory is available. The list is used to find a block of memory large enough to allocate to the object at allocation time. This approach is called a “free list”.

There is also a concurrency issue to be aware of. If object A is allocating memory and the pointer position has not been changed, object B will start allocating memory from its original position.

To solve this problem, there are two solutions. One is to synchronize memory allocation. Ensure atomicity of memory allocation. Another solution is to divide the action of allocating memory into different areas, depending on the thread. Each thread allocates memory in its own memory area. This area is called the Local Thread Allocation buffer (TLAB). If the memory in this area is insufficient, apply for a new area synchronously.

After the memory allocation is complete, the virtual machine initializes the memory to a value of 0. The default values of some properties are assigned in this step. Such as the default values for int, Boolean, and so on.

You then need to set up the object as necessary. For example, the age of the object, the hash value of the object, the information of the object’s class, and so on. This data is stored in the object header

2. Object access

After the object is created, there are two ways to access the object we have created. Use handles and direct Pointers.

2.1 Access using Handles.

If handle access is used, the virtual machine allocates an extra block of memory for the handle pool. The Java virtual machine stack records the address of the handle to the object. As shown below:

2.2 Direct pointer access

With direct pointer access, the Java virtual machine’s stack records the object’s direct address in the Java heap. As shown below:

Both methods have their advantages. When using handle access, you only need to change the value of the handle when the object is moved (GC), while the reference address in the Java stack does not change.

The biggest advantage of direct pointer method is fast speed, it reduces the time cost of a pointer location.

Reference 3.

  • An in-depth understanding of the Java Virtual Machine (Version 2)