Singleton mode in Design Mode

Source: Internet
Author: User

Singleton mode in Design Mode

Why do we need to spend time and effort writing blogs with so much information on the Internet? I think it is necessary to write my own views on a problem, otherwise it is really unnecessary to write,

You can simply repost another user. In the past, I always felt a little overwhelmed and really ashamed of my own behavior. Let's not talk much about it. Go straight to the question.

The Singleton mode is also one of the most frequently used models. Next we will talk about the simplest way to write the singleton mode:

 

class Singleton1{private static Singleton1 singleton1=new Singleton1();private Singleton1(){}public static Singleton1 getInstance(){return singleton1;}}

This is not a standard form of Singleton mode. You can write it as needed. It is not difficult to see from the above:

 

1: A private method to prevent objects from being instantiated again.

2: a static method returns an instantiated object for executing some methods. Note that this method is static. Otherwise, it needs to be instantiated to execute this method.

The Singleton mode cannot be instantiated again.

Why is Singleton mode?

This is probably because only one instance exists during the running process.

Although the above form meets our needs, from another perspective, if we access any other static domain of this class, what will happen?

This will cause all static variables to be loaded, which may cause us to never use this variable and waste resources.

Since it may be a waste of resources, make some adjustments to it.

 

class Singleton1{private static Singleton1 singleton1=null;private Singleton1(){}public static Singleton1 getInstance(){if(singleton1==null){singleton1=new Singleton1();}return singleton1;}}

Maybe you think this is perfect, but is it practical to consider concurrency?

 

First, we need to talk about the steps for java to instantiate an object:

1: allocate memory space

2: Initialize the constructor

3: point the memory address to the allocated memory space

This is a process of jvm object initialization. The sequence of the 2, 3 parts may change. After all, optimization will be taken into account during jvm design, and the optimization algorithm will perform this process.

Commands are theoretically changed to achieve the expected efficiency.

This reminds us of the above problems?

If 100 people log on and call the configuration file to read the configuration file, that is, access to the single instance, can we ensure that only one instance is created?

The following is a simple example:

 

for(int i=0;i<100;i++){    new Runnable() {                        public void run() {            Singleton1.getInstance();        }    };                }

Now we have the first thread. We have detected that singleton1 is null to create a class to create an instance. However, before the instance creation is complete, the second thread has arrived. However, he still detects that singleton1 is null.

 

In this case, we cannot guarantee that only one instance is created, so our Singleton has an error.

Since writing in this way is not thread-safe, what should we do in this situation?

First, we think of locking and synchronizing code blocks. After all, the lock mechanism is designed to synchronize code.

Then we have another method:

 

class Singleton1{private static Singleton1 singleton1=null;private Singleton1(){}public static synchronized Singleton1 getInstance(){if(singleton1==null){singleton1=new Singleton1();}return singleton1;}}

The disadvantage of this method is obvious. If we have 1000 threads, we cannot wait until all the threads are judged. This way, our efficiency will be as low as an unacceptable one.

 

Therefore, we cannot accept this writing method, so we have another writing method:

 

public static synchronized Singleton1 getInstance(){if(singleton1==null){synchronized(Singleton1.class){if(singleton1==null){singleton1=new Singleton1();}}}return singleton1;}

 

It is understandable to judge whether the value is null for the first time, but why should we judge the value of null?

This depends on our process? Our thread 1, 2, 3, thread 1 and 2 are all executed after the first null judgment, then thread 1 is instantiated, the object is instantiated, and thread 2 is in, But thread 2 does not know

After the instance is instantiated, it will be instantiated again, and thread 3 can directly judge that it is not null and directly skip the lock synchronization code, this improves efficiency and avoids errors.

I think so too, but we mentioned the process of instantiating an object in jvm. In this case, can we ensure that there is no problem?

If the instantiation object of jvm is the same as the step sequence of 1, 2, and 3, this is correct, but we cannot guarantee that the sequence is changed to 1, 3, 2, if the order is 1, 3, and 2

What is the situation?

This may cause us to point the stack address to the object in the heap in advance, which will lead to the waiting thread 2 mistakenly believing that thread 1 has completed the instantiation of the object, but there is no initialization process, this directly causes our thread 2 to return an object without initialization. At this time, we will ask, isn't there a single case that theoretically has no problem? This is too cool.

Of course, if not, is there any significance for our Singleton model?

The following describes our final mode:

 

public class Singleton {  private Singleton(){}  public static Singleton getInstance(){ return SingletonInstance.singleton;  }  private static class SingletonInstance{       protected static Singleton singleton = new Singleton();   } }

Using the internal class structure, we can avoid the above problems, which can solve both the efficiency problem and the problem of Code Synchronization. Can we use the locking mechanism to complete the final operation?

 

This is of course possible. We can consider the issues that java developers can certainly consider. After jdk1.5, there will be volatile, this function is equivalent to canceling the command optimization cancellation during jvm instantiation. As long as we add this keyword to the object, the 1, 2, 3 will be executed in this order, but it will be useful after jdk1.5.

I have been thinking about this article for a long time, and I have also referred to a lot of materials, which can help me a lot and hope to help people who are learning. Of course, please tell me what's wrong. The technical team is the best engineer.

 

 

 

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.