Creating a method in a singleton mode 2

Source: Internet
Author: User

1.java Mode single case mode

The singleton mode ensures that a class has only one instance, provides this instance on its own and provides this instance to the system as a whole.

Features: 1, a class can have only one instance 2, and create this instance 3, the entire system to use this instance singleton mode the main function is to ensure that in Java applications, only one instance of class classes exists. Such a single-threaded operation is required in many operations, such as establishing a directory database connection. Some resource managers are often designed as singleton patterns. External resources: for example, each computer can have several printers, but only one printer Spooler to prevent both print jobs from being output to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to avoid a communication port being called simultaneously by two requests.

Sometimes there is a need for a class to have only one instance of the object globally at the time of the system running, and to get the object instance to be fetched only through the object class-specific provider to bypass the regular constructor to avoid instantiating multiple class object instances in the global run environment. In the face of such a demand, how to provide a encapsulation mechanism to ensure that an object class has only one instance? It is important to note that when a client uses the object class, it does not consider whether this class has only one instance of the problem, which should be the responsibility of the Class Designer, which is guaranteed, not the responsibility of the class user. At the same time, because this globally unique object instance has all the "power" of the owning class, it is naturally responsible for exercising these powers! That's what we're talking about--a single-case pattern!

2. Intentions

Ensure that a class has only one instance and provides a global access point to access it.

Structure diagram

    1. Singleton (singleton) Role: Defines a instance operation that allows a client to access its unique instance. Instance is a class operation, usually a static method, that is responsible for creating its own unique instance.
code example
1: Public  class Singleton {
2:      static Singleton instance=null;
3:      private Singleton () {
4:  
5:      }
6: Public      static Singleton Instance () {
7:          if (instance==null) {
8:              instance=new Singleton ();
9:          }
Ten:          return instance;
One:      }
:      //Omit other function methods ...
:  }

The example code above is the simplest implementation of Singleton mode, realizes the basic requirement of Singleton mode, provides a global access point to get the Singleton object instance, and sets the constructor access modifier of the Singleton class to private. Prevents client programs from creating object instances of singleton classes directly through new, guaranteeing the global uniqueness of the objects. Of course, this is just the sample code, in the actual production environment, we need to based on thread safety, performance and other aspects to transform the implementation of the singleton mode, the below will be explained in detail.

Realistic Scenarios

In our daily life, there are a lot of common scenarios that are very similar to what we are talking about in the singleton pattern. For example, each computer can have a lot of printers, but there can only be one printer Spooler, so that two print tasks are not output to the printer at the same time; the presidency of the country is a singleton model, since our national Constitution stipulates that at any one time the state can have only one president of the country (not including the Vice-Chairman), So, regardless of the current president's personal status, we can always through the president of the People's Republic of China to obtain all the information of the current President, in other words, it is only through it to exercise the various powers and obligations conferred on it by the Constitution, because of its "global uniqueness". Another example is the spring open source framework, which is commonly used in our daily web development, to specify the number of object instances created by various beans, the scope= "singleton", the purpose of which is to sue the spring container, which only has one global instance at run time. , that is, any place quoted is the only instance of the object, in-depth spring source code, we can not find, in fact, its internal is basically a singleton model implementation only.

Next, we focus on the different implementations of the singleton pattern and its characteristics. This is also the most significant part of the singleton pattern, I hope that we all together to learn, understand and master their differences.

The sample code is one of the simplest examples of implementations that can be used in a single-threaded environment, but if placed in a multithreaded environment, it is a thread-safe issue. The reason for this is that multiple singleton objects may appear. Let's illustrate how the instance () method for getting singleton objects in the sample code is created at run time with two so-called Singleton objects, and now assumes that there are two pairs of threads A and B, and they call the instance () method at the same time. Then the actual execution process is likely to be:

If you follow the order of execution, then both A and B threads here create a singleton instance object, which violates the nature of the singleton pattern. The singleton pattern implementation in the sample code is lazy , and if thread safety is required, there are usually two ways, one is to add the sysnchronized keyword to the instance () method, namely:

1: Public  static synchronized Singleton Instance () {
2:      if (instance==null) {
3:          instance=new Singleton ();
4:      }
5:      return instance;
6:  }

The keyword synchronized will guarantee the thread safety of the instance () method, but this will reduce the overall access speed and need to be judged every time. Is there a better way to implement the lazy way to implement the thread - safe and to ensure the efficiency of execution?

The answer is double locking mechanism , specifically refers to: not every time into the instance () method need to synchronize, but first out of sync, enter the method after, first check the existence of the instance, if it does not exist before entering the following synchronization block, this is the first re-ticket. After entering the synchronization block, check again if the instance exists, and if it does not exist, create a singleton object instance in the case of synchronization, which is the second check. In this way, only one synchronization is required, which reduces the time wasted in the synchronization of the judgment.

The implementation of the double-check lock mechanism uses a keyword volatile, which means that the value of the variable modified by the volatile will not be cached by the local thread, and all reads and writes to the variable are directly manipulated to share the memory, thus ensuring that multiple threads can handle the variable correctly. It is important to note that in the java1.4 and previous versions, many JVMs have problems with the volatile keyword implementation and are recommended for use on Java5 and above. The implementation code is as follows:

1: Public  class Singleton {
2:      private static volatile Singleton instance=null;
3:      private Singleton () {
4:  
5:      }
6: Public      static  Singleton Instance () {
7:          if (instance==null) {
8:              synchronized (singleton.class) {
9:                  if (instance==null) {
Ten:                      instance=new Singleton ();
One:                  }
:              }
:          }
:          return instance;
:      }
:  }

One thing to mention here is that because the volatile keyword may block out some of the necessary code optimizations in a virtual machine, it is not very efficient to run. It is therefore generally recommended that there is no special need and is not recommended. In other words, while using a dual-lock mechanism, you can implement a thread-safe singleton pattern, but it is not recommended to use it extensively. Since this is the case, is there a more reasonable way to complete the implementation of the singleton pattern?

There are also two options, one is the A hungry man-type implementation, one is the lazy way to achieve .

a hungry man- type implementation is relatively simple, directly in the Singleton class loading process, the static type of instance variable instantiation, by the virtual to ensure its thread security, the only thing is not able to implement lazy loading, but this way, The case is already efficient enough, and the implementation is relatively straightforward , as shown in the sample code:

1: Public  class Singleton {
2:      static Singleton instance=new Singleton ();
3:      private Singleton () {}
4:  
5: Public      static Singleton Instance () {
6:          return instance;
7:      }
8:  }

But there is also a lazy way to realize, name day: Lazy Initialization holder class mode, which combines Java class-level internal classes and multi-threaded default synchronization lock knowledge, It is very clever to implement both lazy loading and thread safety at the same time, before introducing its concrete implementation, we should first popularize the basic knowledge!

What is a class-level inner class , which refers to a member-style inner class with a static adornment, or an inner class that has no static adornment, is called an object-level inner class. a class-level inner class is equivalent to the static component of its outer class, which has no dependency on the object from the Outer class object and can therefore be created directly . In a class-level inner class, you can define a static method that can only refer to static methods or static member variables in an external class in a static method. Class-level internal classes are equivalent to members of external classes and are loaded only when they are first used.

Next, let's look at the cases in which the JVM implicitly performs a synchronous operation for us, in which case we don't need to do synchronization control ourselves:

    1. When the data is initialized by a static initializer (either on a static field or an initializer in a static{} block).
    2. When you access the final field.
    3. When the object is created before the thread is created.
    4. The thread can see the object it will be working on.

With the above two parts of the knowledge, and then to understand this efficient single-instance implementation is relatively simple!

Lazy Type:

1: Public  class Singleton {
2:      //Class-level inner class that has no binding relationship to an external class instance and is loaded only when called, enabling lazy loading
3:      private static Class singletonholder{
4:          //static initializer, guaranteed by the JVM for thread safety
5:          private static Singleton instance=new Singleton ();
6:      }
7:  
8:      Private Singleton () {}
9:  
Ten: Public      static Singleton Instance () {
One:          return singletonholder.instance;
:      }
:  }

In combination with the basics and the comments on the code, think about it, isn't this a clever approach? When the instance () method is called for the first time, It first reads singletonholder.instance, causing the Singletonholder class to be initialized, and when the Singletonholder class is loaded and initialized, its static domain is initialized, and the object instance of Singleton is created because it is a static domain because This is initialized once when the class is loaded by the virtual machine and is guaranteed to be thread-safe by the JVM . To sum up, the implementation of this method, not only to achieve the delay load, but also to achieve a thread safety, is really a recommended single-instance implementation method, we have a good understanding of the subtleties of this method! (From the "Grinding design Mode" book)

Implementation Essentials
    1. Singleton mode mode is used to restrict the creation of Singleton class instances
    2. The constructor for the singleton class can be protected, a quilt class derivation
    3. The singleton class generally does not need to implement the Cloneable interface, because cloning operations can result in multiple singleton objects that are associated with the original intent of the singleton pattern
    4. In the case of singleton cases, the single-case mode concerns are not related to the destruction management of the instances, we can accomplish the management of the various singleton instances by using a single-case registry.
Application effect
    1. Object Instance control: Singleton mode provides a global access point, guaranteeing that only one singleton instance object is accessible to the client.
    2. Convenience of creation: because the Singleton class controls the creation of instances, it is easy to modify the instantiation process of the singleton object according to the actual situation.
    3. Because singleton mode cannot directly create singleton objects through new, the use of singleton classes must be known in advance that the class is a singleton class, otherwise the impression of poor usability of the class is due to the inability to see the source code.
    4. Because the Singleton class has only one object instance globally, there may be more than one reference to it because it cannot be destroyed simply by destroying this particular object instance, in other words it is not easy to manually destroy the object. In the memory management language, this problem we can not pay too much attention to this problem, the runtime will help us automatically destroy the objects that do not already exist, but for the C + + language, if the simple destruction of the Singleton object, it is possible to create a "floating reference" problem.
4 single-Case mode 2 ways:

A Hungry man type
Class Singleton {
private static Singleton instance=new Singleton ();
Private Singleton () {}
Static Singleton getinstance () {
return instance;
}
}
Lazy type
Class Singleton {
private static Singleton Instance=null;
Private Singleton () {}
Static Singleton getinstance () {
if (instance==null)
Instance=new Singleton ();
return instance;
}
}

Creating a method in a singleton mode 2

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.