/* A single example under Multithreading */ // a hungry man type class single{ privatestaticfinalnew single (); Private Single () {} Public Static Single getinstance () { return s; }}
/*lazy Join synchronization in order to solve multi-threaded security issues. Double judgment is added to solve the problem of efficiency. */classsingle{Private StaticSingle S =NULL; PrivateSingle () {} Public StaticSingle getinstance () {if(s==NULL) { synchronized(Single.class) { if(s==NULL) //-->0-->1s =NewSingle (); } } returns; }}classsingledemo{ Public Static voidMain (string[] args) {System.out.println ("Hello world!"); }}A better single-instance implementation method
The A Hungry man-type singleton class cannot implement lazy loading, regardless of the future use of memory, lazy single-class thread safety control cumbersome, and performance is affected. Can be seen, whether it is a single case of a hungry man or lazy, there is such a problem, there is no way to be able to overcome the shortcomings of the two single cases, and the advantages of both? The answer is: yes! Let's learn this better technique known as initialization Demand Holder (Iodh) .
In Iodh, we add a static (static) inner class to the Singleton class, create a singleton object in the inner class, and return the singleton object to external use through the getinstance () method, as shown in the following code:
//initialization on Demand HolderclassSingleton {PrivateSingleton () {}Private Static classHolderclass {Private Final StaticSingleton instance =NewSingleton (); } Public StaticSingleton getinstance () {returnholderclass.instance; } Public Static voidMain (String args[]) {Singleton S1, S2; S1=singleton.getinstance (); S2=singleton.getinstance (); System.out.println (S1==S2); } }
Compile and run the code above and run the result: true, the Singleton objects created S1 and S2 are the same object. Because static singleton objects are not instantiated directly as member variables of Singleton, the class loads without instantiating Singleton, and the first call to getinstance () loads the inner class Holderclass, A static type of variable instance is defined in the inner class, at which point the member variable is initialized first, and the Java Virtual Machine guarantees its thread security, ensuring that the member variable can only be initialized once. Because the getinstance () method does not have any thread locking, its performance has no effect.
by using Iodh, we can implement both lazy loading and thread safety without compromising system performance, which is one of the best implementations of the Java language Singleton pattern (the disadvantage is that it is related to the characteristics of the programming language itself, and many object-oriented languages do not support Iodh).
Java Multithreading under single example