Android design mode-singleton mode and android Design Mode
Android design mode-in singleton mode, under what circumstances do you need Singleton mode?
- Some classes provide public functions for others to call and do not process the business logic.
- Classes are called by many classes and threads.
Design Singleton Mode
public class Singleton{private static Singleton mSingleton;private Singleton(){}public static Singleton getInstance(){if(mSingleton == null){ mSingleton = new Singleton();\\A } return mSingleton; }}
The preceding method may cause problems when multithreading occurs. For example, if two threads call getInstance () at the same time, two new objects are generated.
Singleton mode Improvement 1
public class Singleton{private static Singleton mSingleton;private Singleton(){}public static Singleton getInstance(){ synchronized(Singleton.class){ if(mSingleton == null){ mSingleton = new Singleton();\\A } return mSingleton; } }}
This method still has a problem, that is, in the case of high concurrency, multithreading is used to snatch the lock. If there are hundreds of threads, one of which is less lucky, this thread will continue to go to getInstance, resources are not returned, and the UI is not updated.
Singleton mode Improvement 2
public class Singleton{private volatile static Singleton mSingleton;private Singleton(){}public static Singleton getInstance(){ if(mSingleton == null){\\A synchronized(Singleton.class){\\C if(mSingleton == null) mSingleton = new Singleton();\\B } } return mSingleton; }}
Note: volatile prevents the cpu from re-sorting instructions and prevents code order changes.
This method is better because all the threads will be synchronized when the instance is created for the first time, and will be directly returned if the instance is obtained later.
But it seems that some people still have doubts about the code. Why do we need to judge it as null twice?
In fact, this is to prevent multiple threads from entering the first if at the same time. For example, thread A executes to line A, thread B executes to line B, and thread B does not return. When thread A executes to line C, thread B initializes the instance. If there is no further judgment, two instances will be generated! Therefore, it makes sense to judge null twice.