Android design mode-Singleton mode under what circumstances do I need a singleton mode?
- Some classes provide common functionality for others to invoke and do not handle business logic by themselves
- Classes are called by many classes and threads
Design a singleton mode
publicclass Singleton{privatestatic Singleton mSingleton;privateSingleton(){}publicstaticgetInstance(){ifnull){ new Singleton();\\A } return mSingleton; }}
The above approach can cause problems in multithreading, such as having two threads calling getinstance () at the same time, and then a new two object.
Single-instance mode improvement 1
publicclass Singleton{privatestatic Singleton mSingleton;privateSingleton(){}publicstaticgetInstance(){ synchronized(Singleton.class){ ifnull){ new Singleton();\\A } return mSingleton; } }}
This way still has the problem, is high concurrency in the case of multi-threaded to snatch the lock, if there are hundreds of threads, one of which has a bad luck, the thread will appear to go getinstance, the resources have been returned not to go back, the UI will not be updated.
Single-instance 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 ) m Singleton = new Singleton (); \\b}} return Msingleton; }}
Note: Volatile is to prevent the CPU from being re-ordered, preventing code order from being changed.
The good thing about this approach is that all the threads are synchronized the first time the instance is created, and then the instances are returned directly.
But looking at the code as if someone would have doubts, why do you need to judge two times to be null?
In fact, this is meant to prevent multiple threads from entering the first if, for example, thread a executes to line A, thread B executes to line B, thread B has not returned. When thread a executes to line C, then thread B initializes the instance, and if there is no judgment inside it will generate two instances! So it makes sense to judge Null two times.
Android design mode-Singleton mode