This article is from — Coke Coke, the author’s homepage link: Coke Coke personal homepage
In singleton mode, to keep efficiency and thread safety, we’ll look at this code double checklock
public class SingletonLazy {
private volatile static SingletonLazy data;
private SingletonLazy(a){
System.out.println("Initialize");
}
public SingletonLazy getData(a) {
if (data == null) {
synchronized (SingletonBase.class){
data=newSingletonLazy(); }}returndata; }}Copy the code
Important: Critical sections must be class objects, and properties must be volatile. The property must be volatile, otherwise it will be unsafe
Volatile is a Java keyword that prevents directive reordering and ensures visibility. Volatile prevents directive reordering. Instruction reordering exists in the running process of a machine (the purpose is to improve the utilization of machine resources), but instruction reordering is a hidden danger to programming, Happens Before principle
During object initialization, data=new SingletonLazy(); This line will be compiled into four commands at the bytecode level
Javac XXXX. Java Compiles the bytecode. Javap -v xxxxx.class is recommended for viewing the bytecode
The results are as follows
- The new step opens up space and allocates that space to the object
- Dup initially initializes the object (assigned 0)
- Invokespecial is a user-defined constructor
- Putstatic assigns a value to a reference
Under the happens-before principle, the order of steps 1 and 2 will not change, but steps 3 and 4 will be reordered: the reference gets the object value before the constructor executes
We introduced volatile in case the object was not initialized, disallowing reordering of steps 3 and 4 to ensure thread-safety