What is the problem with a single meeting?
If multiple threads call this instance at the same time, there will be a thread security issue
What is the general use of a single case?
The purpose of the singleton is to ensure that there is only one instance of the runtime, the most common places such as getting a connection to a database, or creating a beanfactory operation in spring, which calls their methods to perform a particular action.
First come to know the next two models: the bad-Chinese type of lazy
Public classMyFactory {////A Hungry man-create now//private static MyFactory instance = new MyFactory ();//Public static MyFactory getinstance () {//return instance;// } //lazy use of the time in the creation, do not have to create (thread security issues) Private StaticMyFactory instance = null; Public Staticmyfactory getinstance () { instance = new myfactory (); returninstance; } }
Here are a few ways to address thread safety:
Method One: In myfactory is joined by a private static inner class , externally supplied interface is getinstance () method, that is, only in myfactory . getinstance (), the instance object is created, and no synchronization is used. Guaranteed to have only one instance, and also has the lazy characteristics
Public class myfactory { privatestaticclass instanceholder { public staticnew myfactory (); } Public Static myfactory GetInstance() { return myfactory. Instanceholder. instance; } }
Test code
Import Staticorg.junit.assert.*;Importorg.junit.Test; Public classmyfactorytest {@Test Public voidTestgetresource () {myfactory mf1=MyFactory. getinstance (); MyFactory Mf2=MyFactory. getinstance (); System.out.println (MF1!=NULL);//trueSystem.out.println (mf1 = = MF2);//true }}
Way two: (Lazy type)
This approach also does not use synchronization, and ensures that the MyFactory reference is created when the static getinstance () method is called.
Private Static New myfactory ();
Public Static myfactory getinstance () { return instance; }
Test code: Same Method one
Way Three: Use synchronized , Usually the entire method is locked into a resource-intensive , the actual multithreaded access problem is this code instance = new MyFactory ();
in order to reduce the consumption of resources, just lock this sentence on the line, Two threads enter the first time to determine if the instance is empty inside the IF statement, one thread obtains the lock to perform the new operation, and the other thread is blocked,
When the first thread finishes executing, it is not safe for the second thread to make a new operation directly. To avoid a second new operation, add a second condition judgment, which is checked two times
Private StaticMyFactory instance; Public Staticmyfactory getinstance () {if(Instance = =NULL){ synchronized(MyFactory.class) { if(Instance = =NULL) {instance=Newmyfactory (); } } } returninstance; }
Test code with Method one
A summary of thread safety problems in single-instance mode