NOTE
7.14 Object Creation Process
Code, bytecode, explanation, and a proposed solution for object-creation instruction reordering.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Code
public class Test
{
private Integer val = 10;
public static void main(String[] args)
{
Test test = new Test();
}
}
2. Bytecode

2.1. Explanation
It can be seen that Test test = new Test(); is divided into three steps:
- Create a Test instance.
- Assign a value to the
valproperty of the Test instance. - Assign the reference of the Test instance to the
testvariable.
After the first step is completed, the object is in a partially initialized state.
The issue is with steps 2 and 3. These two steps do not have a strong dependency, so according to CPU pipeline technology, these two instructions may be reordered, meaning the execution order may become 1-3-2.
2.2. Solution
Add the volatile modifier to the val variable to prohibit instruction reordering.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub