Through the singleton mode, we can ensure that there is only one instance of a class in the system and the instance is easily accessible to the outside world, thus facilitating the control of the number of instances and saving system resources. Java Singleton schema definition: "A class has only one instance, and it instantiates itself to the whole system.
The core knowledge points are as follows:
(1) The construction method of the class using the singleton design pattern will be privatized (with private modification).
(2) Instance objects of this class are generated inside it and encapsulated as private static types.
Why instantiate objects as static?
One is to instantiate an object outside the class, use the method to use the object pair, or use the "class. method name ()", because the constructor is private, the object can not be instantiated outside the class, so the second method can only be used. In this case, the method is static, and the static method cannot access non-static members, so the instance variables of the instance defined in the class must also be static.
(3) Define a static method to return an instance of the class.
When to use the singleton mode:
When there are multiple instances that can cause program logic errors
2. Benefits:
1. Reduce memory usage
2. The singleton pattern prevents other objects from instantiating copies of their own singleton objects, thus ensuring that all objects have access to a unique instance.
3. Because classes control the instantiation process, classes can flexibly change the instantiation process.
Three Models of Single Case Model
- 1. Hungry Chinese Style
package com.sunru.day0628; /** * Hungry Chinese style - is poor, not ready, afraid of starvation. Class loading is ready * */ public class SingleInstance { // Define a private constructor that cannot be instantiated outside the class private SingleInstance() { } // Some will add final modifier (more rigorous), after adding final modifier, the reference pointed can not be changed. // This is the use of final: final member variables represent constants, which can only be assigned once, and the value can not be changed after assignment. // This sentence needs to be understood as follows: // For a final variable. // If it is a variable of basic data type, its value cannot be changed once initialized. // If it is a variable of reference type, it cannot be pointed to another object after initialization. private static final SingleInstance singleInstance = new SingleInstance(); // Static methods return instances of this class public static SingleInstance getInstance() { return singleInstance; } }
The first method is the legendary Hungry Han model.
The advantages are: it is simple to write, and there is no multi-threaded synchronization problem, avoiding the performance problems caused by synchronized;
The disadvantage is that when the class SingletonTest is loaded, the instance of static is initialized, the static variable is created and allocated memory space. Since then, the instance object of the static occupies the memory (even if you haven't used the instance yet). When the class is unloaded, the static variable is destroyed and the memory occupied is released, so under certain conditions. Next will consume memory.
- 2. Lazy (and full) style -- Delayed loading
package com.sunru.day0628; /** * * Full-boiled (lazy-boiled) - new when you use it (thread insecurity) * */ public class SingleInstance1 { // Define a private constructor (to prevent de-instantiation through new Single Instance 1 ()) private SingleInstance1() { } //Define a variable of type Single Instance 1 (not initialized, note that the final keyword is not used here) //You can't add final to this because you have to assign it to him again elsewhere. //With final, null is always the default, and it can't be assigned to this property again. //This property is static, so it is possible to share data with multi-threaded concurrent operations. Then the following thread insecurity will occur. private static SingleInstance1 singleInstance1; // Define a static method (Singleton Test is initialized when invoked, but repeated initialization may occur when multithreaded access is made) public static SingleInstance1 getInstance() { if (singleInstance1 == null) { //In this place, when multithreaded, //Maybe thread A hangs and this property is null, so thread B may also judge that condition OK is coming in. //Then when thread A can execute, it will have new objects, and thread B will have new objects. //There is no guarantee of memory uniqueness. Thread insecurity singleInstance1 = new SingleInstance1(); } return singleInstance1; } ///** // * In order to deal with the above insecurity, we can simply add [synchronized] to the method to make it a synchronization function. // * But: // * In the case of many threads, the lock must be judged for each thread access, and efficiency is the problem. So there's the back [double lock form] // */ //public static synchronized SingleInstance1 getInstance() { // if (singleInstance1 == null) { // singleInstance1 = new singleInstance1(); // } // return singleInstance1; //} }
The second method is the legendary "satiety mode"
Advantages: It's easy to write. When the class SingletonTest is loaded, instances of static variables are not created and allocated memory space. When the getInstance method is called for the first time, instance variables are initialized and memory is allocated, so memory is saved under certain conditions. When using synchronized keywords to avoid multithreaded access, multiple Sin variables appear. An example of gletonTest.
The disadvantage is that the efficiency of synchronization method is slightly low when it is frequently called.
- 3. Double Judgment Model
This mode decentralizes synchronization content to if and improves the efficiency of execution. It does not need to synchronize every time an object is acquired.
Synchronization is only the first time, and it's not necessary after it's created. Avoid creating singletons in Tuhao mode, which may cause thread insecurity.
package com.sunru.day0628; /** * Double lock form * This mode decentralizes synchronization content to if and improves the efficiency of execution. It does not need to synchronize every time an object is acquired. * Synchronization is only the first time, and it's not necessary after it's created. Avoid creating singletons in Tuhao mode, which may cause thread insecurity. * */ public class SingleInstance2 { private SingleInstance2(){ } private static SingleInstance2 singleInstance2; /** * When static methods are synchronized, the lock used is not this, but class. */ public static SingleInstance2 getInstance(){ if(singleInstance2==null){ //There may be multiple threads in this place, in this queue, ABCD.. synchronized(SingleInstance2.class){ if(singleInstance2==null){ //Suppose the first thread A comes here and then hangs. At this time, the singleton object has not been created. // Suppose that at this point, the B thread also comes to determine that the singleton object== null is valid, but because the A thread has locked the if judgment of the inner layer, so B can only wait outside. //Assuming that thread A is awakened, the singleton will be assigned the following statement, and the singleton object will be created. Then release the lock. B You can come in. //After thread B comes in, we first judge whether the singleton object is null, and find that it is no longer null, then we do not need to create it. //CD threads, too, //If the first if doesn't come in, then the lock won't be judged. singleInstance2 = new SingleInstance2(); } } } return singleInstance2; } }
Method 4 is the best implementation of the singleton pattern. Memory occupancy, high efficiency, thread safety, multi-threaded operation atomicity