1. Hungry-style singleton model
(1) Hungry-style singleton pattern concept
The Hungry-style singleton pattern is initialized immediately when the class is loaded and a singleton object is created . It is absolutely thread-safe . It is instantiated before the thread appears. There is no access security problem.
(2) Code implementation
public class HungrySingleton {
private static final HungrySingleton hungrySingleton = new HungrySingleton();
private HungrySingleton(){
}
public static HungrySingleton getInstance(){
return hungrySingleton;
}
}
(3) Advantages and disadvantages
- Advantages: high execution efficiency, high performance, no locks
- Disadvantages: In some cases, it may cause memory waste, reflection destruction, and serialization destruction of singletons.
(4)Usage scenarios
- The Hungry-style singleton pattern is suitable for situations where there are few singleton objects. Writing this way can ensure absolute thread safety and relatively high execution efficiency.
- But its shortcoming is also obvious, that is, all object classes are instantiated when they are loaded. If there are a large number of singleton objects in the system, system initialization will cause a lot of memory waste.