1 Packageconcurrent;2 3 /**4 * Single case design mode with multi-threaded (1) load immediately with a hungry man mode (2) lazy loading with lazy mode (3) built-in static class to implement a singleton design pattern5 * (4) Enumeration class implements a singleton design pattern6 * 7 * @authorFoolishbird_lmy8 * 9 */Ten classSingletona { One //load immediately with a hungry man mode A Private StaticSingletona SA =NewSingletona (); - - PrivateSingletona () { the - } - - Public StaticSingletona getinstance () { + returnsa; - } + } A at classsingletonb { - //Lazy Loading with lazy mode, double check mode - Private Staticsingletonb sb; - - Privatesingletonb () { - in } - to Public Staticsingletonb getinstance () { + //Lazy Loading - if(SB = =NULL) { the synchronized(SINGLETONB.class) { * if(SB = =NULL) { $SB =Newsingletonb ();Panax Notoginseng } - } the } + returnsb; A } the } + - classSingletonc { $ //Inner class $ Private Static classsingletonhandler{ - Private StaticSingletonc sc =NewSingletonc (); - } the - PrivateSingletonc () {Wuyi the } - Wu Public StaticSingletonc getinstance () { - returnSingletonhandler.sc; About } $ } - - enumsingletond{ - //implementing singleton patterns using enum enum classes A INSTANCE; + Public voidget () { the System.out.println (); - } $ } the classSingletonthreadextendsThread { the Public voidrun () { the System.out.println (Singletona.getinstance (). Hashcode ()); the System.out.println (Singletonb.getinstance (). Hashcode ()); - System.out.println (Singletonc.getinstance (). Hashcode ()); in System.out.println (SingletonD.INSTANCE.hashCode ()); the } the } About the Public classTestsingleton { the Public Static voidMain (string[] args) { theSingletonthread St1 =NewSingletonthread (); +Singletonthread St2 =NewSingletonthread (); -Singletonthread ST3 =NewSingletonthread (); the St1.start ();Bayi St2.start (); the St3.start (); the } -}
1. Bad Han: Because the instance is created when the class is loaded, it is thread safe (except when multiple ClassLoader exist). The disadvantage is that the load cannot be delayed.
2, lazy: need to lock to achieve multi-threaded synchronization, but the efficiency will be reduced. The advantage is delayed loading.
3, double check Lock: Trouble, in the current Java memory model does not necessarily work, some platforms and compilers even wrong, because SB = new SINGLETONB () This code on different compilers behavior and implementation of unpredictable.
4, Static internal class: Lazy loading, reduce memory overhead. Because it is only loaded when it is used, the static field avoids the drawback of the permanent generation that enters the heap memory when the Singleton class loads (most garbage collection algorithms do).
5. Enumeration: Very good, not only can avoid multithreading synchronization problems, but also prevent deserialization to recreate new objects.
Implementation of single-instance design pattern under multithreading