Creation Mode -- (re-talk) Singleton mode -- Re-talk

Source: Internet
Author: User

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 _






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.