Preface : Java is often used in a single case, today found that they have a little new understanding.
Lazy Single-case
PackageCom.mwq.singleton; Public class Singleton1 { Private Singleton1() { }Private StaticSingleton1 single =NULL; Public StaticSingleton1getinstance() {if(single =NULL) {return NewSingleton1 (); }returnSingle } PublicStringSayHello() {return "Hello Singleton1"+ This; }}
This method is used in the first time a singleton instantiation, I used to use this way, but did not think this is a thread is not safe, and later will write an example of proof. private static Singleton1 single = null;Why not add the final keyword, because this lazy style is not final!
A hungry man type single case
PackageCom.mwq.singleton; Public class Singleton2 { Private Singleton2() { }Private Static FinalSingleton2 single =NewSingleton2 (); Public StaticSingleton2getinstance() {returnSingle } PublicStringSayHello() {return "Hello Singleton2"+ This; }}
This method is instantiated at the same time that the class was created, and the private constructor is only called once, which guarantees that it is safe.
Enumeration single-Case
package com.mwq.singleton;publicenum Singleton3 { INSTANCE; publicsayHello() { return"hello singleton3"this; }}
The writing was quicker, and I never knew it before.
Provides a free serialization mechanism, absolutely prevents multiple instantiation, even in the face of complex serialization or reflection attacks, is undoubtedly the best way to implement Singleton. -–effective Java Book
For the previous two kinds of is possible by the setAcceessible() method of reflection attack, but I did not find how to avoid?????
Argument
PackageCom.mwq.singleton; Public class Test extends Thread{ Public Static void Main(string[] args) { for(inti =0; I <Ten; i++) {NewThread (NewTest ()). Start (); } }@Override Public void Run() {System.out.println (Singleton1.getinstance (). SayHello ()); System.out.println (Singleton2.getinstance (). SayHello ()); System.out.println (Singleton3.INSTANCE.sayHello ()); System.out.println (); }}
Through the above method to test, to obtain the following content:
hello [email protected]1b1aa65hello [email protected]1125127hello singleton3INSTANCEhello singleton1com.mwq.singleton.Singleton1@bb7465hello [email protected]2a5330hello [email protected]1125127hello singleton3INSTANCEhello [email protected]1125127hello singleton3INSTANCE
It can be seen that the lazy singleton is indeed unsafe, creating multiple instances, and the second and third are safe.
Summary : This article refers to the Java design pattern of the singleton mode blog, and the effective Java Chinese version of the book.
Java: A single-instance understanding