The internal class declaration is static: it can be used without initializing the external class. The internal class is loaded and initialized only when it is used by itself, but its internal class is not initialized. for details, see when the class is loaded or when the class is loaded. First, when the class object is generated, the class and all its parent classes will be loaded. Second, when accessing the static members of the class; third: class. forName (Class Name); optimized lazy
We know that lazy has saved space, but it uses synchronization to solve thread security problems, greatly reducing program efficiency.
So we thought about how to improve the efficiency of the lazy style. First, it still needs to be synchronized.
One way isDual Check MechanismThis is widely used in C language, but it is wrong in java. If you lock the basic type, there is no problem, however, if you are locking an object, there will be problems. but here we talk about the singleton mode, so the lock must be an object instead of int, long, double, and other data types.
The following code is incorrect.
public class SingletonLazy01 { private static SingletonLazy01 single = null ; private SingletonLazy01(){ } public static SingletonLazy01 getInstance(){ if(single == null){ synchronized(SingletonLazy01.class){ if(single == null){ single = new SingletonLazy01() ; } } } return single ; }}
We use the volatile keyword
public class SingletonLazy01 { private volatile static SingletonLazy01 single = null ; private SingletonLazy01(){ } public static SingletonLazy01 getInstance(){ if(single == null){ synchronized(SingletonLazy01.class){ if(single == null){ single = new SingletonLazy01() ; } } } return single ; }}
For the dual-check issue, see here ---> dual-check locking and delayed Initialization
19:52:59
Brave, Happy, Thanksgiving!