3.5 a better Singleton Implementation Method
The hungry Chinese Singleton class cannot implement delayed loading, no matter whether it is used in the future, it will not always occupy the memory; the lazy Singleton class thread security control is cumbersome, and the performance is affected. It can be seen that both the hungry and lazy single examples have such problems. Is there a way to overcome the disadvantages of the two single examples, and combine the advantages of the two into one? The answer is yes! Next we will learn this better calledInitializationon demand holder (iodh).
In iodh, we addStatic internal classCreate a singleton object in the internal class, and then return the singleton object to the external using the getinstance () method. The implementation code is as follows:
//Initialization on Demand Holderclass Singleton {private Singleton() {}private static class HolderClass { private final static Singleton instance = new Singleton();}public static Singleton getInstance() { return HolderClass.instance;}public static void main(String args[]) { Singleton s1, s2; s1 = Singleton.getInstance(); s2 = Singleton.getInstance(); System.out.println(s1==s2);}}
Compile and run the code above. The running result is: True, that is, the created singleton object S1 and S2 are the same object. Because the static singleton object is not directly instantiated as a singleton member variable, Singleton is not instantiated during class loading. When getinstance () is called for the first time, the internal class holderclass is loaded, A static variable instance is defined in the internal class. At this time, the member variable is initialized. the Java Virtual Machine ensures thread security and ensures that the member variable can only be initialized once. Because the getinstance () method is not locked by any thread, its performance will not be affected.
By using iodh, we can achieve delayed loading, ensure thread security, and do not affect system performance. This is the best Java Singleton mode.(Its disadvantage is that it is related to the features of programming languages. Many object-oriented languages do not support iodh ).
|
Exercise Load balancer is implemented by using the hunger-type Singleton, the lazy Singleton with dual check lock mechanism, and iodh technology. |
|
So far, we have learned how to implement the three Singleton classes. They areHunger examples, lazy examples, and iodh.
[Author: Liu Wei http://blog.csdn.net/lovelion]