http://blog.csdn.net/ljianhui/article/details/29275655
The singleton mode under multithreading is unsafe
Single-instance mode in Android
There are a large number of singleton classes in Android, such as: Inputmethodmanager class, Calendardatabasehelper class, editable class, and so on. In these classes, there is a method getinstance, where the method either returns the reference to the object directly or determines whether a reference to a class is NULL, if it is not NULL, returns the reference directly, and if NULL, a new object and returns. For example, for the Calendardatabasehelper class, the following code exists:
1 public static synchronized Calendardatabasehelper getinstance (contextcontext) 2 3 if (Ssingleton = = null ) 4 { Ssingleton = Newcalendardatabasehelper (context); 6 7 return Ssingleton; 8 }
As you can see from the code here, the implementation is very similar to what is described above, but because Java does not use the programmer to manage the memory itself, it does not require a reference count, and the method is public static. The synchronized is to ensure that only one thread can enter the method at the same time, which is to prevent the 6th one from the above-mentioned security problem in multi-threaded mode.