Creation Mode -- (re-talk) Singleton mode -- Re-talk
In the Creation Mode-singleton mode article, we mention Singleton mode, that is, a class has only one instance and provides a global access point to it. The problem arises. Let's take the code in the previous article as an example:
<Pre name = "code" class = "java">/*** defines an Instance operation, allowing the customer to access its unique Instance. * Instance is a class operation. * Creates its own unique instance. * @ Author Linhai Gu **/public class Singleton {private static Singleton singleton; private Singleton () {} public static Singleton getInstance () {if (null = singleton) {singleton = new Singleton ();} return singleton ;}}
Now we assume there are two threads: thread A and thread B. Now thread A has accessed
singleton=new Singleton();
We know that when a new object is created, we need to apply for memory allocation. If the application takes several seconds, that is, within these seconds, thread B executes
if(null==singleton)
At this time, thread A has not been applied, singleton is null, and thread B also goes to if. At this time, thread B also applies for memory allocation, which will cause data uniqueness.
Solution:
public class Singleton {private static final Singleton singleton=new Singleton();private Singleton(){}public synchronized static Singleton getInstance(){return singleton;}}
We directly pass a new object to singleton, the member variable of the class. If necessary, we can directly return the result through the getInstance method.
Reprinted please indicate the source: http://blog.csdn.net/hai_qing_xu_kong/article/details/42190605 sentiment control _