Java design mode singleton (Singleton) mode

Source: Internet
Author: User

1. Definition of a singleton pattern

A singleton pattern (Singleton pattern) is a simpler pattern. The original definition is as follows: Ensure a class has only one instance, and provide a global point of access to it. That is, ensure that there is only one instance, and instantiate it yourself and provide this instance to the system as a whole. A generic class for a singleton pattern, for example, is seen:


The Singleton class is called a singleton class, which ensures that only one instance is produced in an application by using the private constructor. and is self-instantiated (in Singleton, its own new Singleton ()). The generic code for a singleton pattern such as the following (this is also known as the A Hungry Man type singleton):

/****************** Singleton Mode: Program Listing 1 ***************************/public class Singleton {private static Singleton instance = New Singleton (); 1. Own internal new one private Singleton () {//2. Private constructor to prevent instantiation of}//3. Provides a public interface. Used to return the object just new out public static Singleton getinstance () {  return instance;} public void Test () {System.out.println ("singleton");}} /********************************************************************/

2. Thread safety problems in Singleton mode

Above is a classic single-instance mode program. And this program does not cause thread synchronization problems. The instance is initialized as soon as the class is loaded for the first time. However, there are other implementations of the singleton pattern, which may cause thread synchronization problems. Take a look at the following examples:

/* * This way is non-thread safe (lazy singleton) */public class Singleton {private static Singleton instance = Null;private Singleton () {}public Static Singleton getinstance () {if (instance = = null) {instance = new Singleton ();} return instance;}}

Why is there a thread safety problem? If a thread a runs to instance = new Singleton (). But the object is not yet acquired (initialization of the object takes time), and the second thread B is also running. When running to inferred instance = = null. Then thread B Gets the condition is also true, so also into the instantiation of instance, then thread a obtained an object, thread B also obtained an object, in memory there are two objects!

There are a number of ways to solve thread-safety problems, such as we can add Synchronizedkeyword to the getinstance () method, such as the following:

public static synchronized Singleton getinstance () {          if (instance = = null) {              instance = new Singleton ();          }          return instance;  
However, the Synchronizedkeyword lock is this object, the use of this method will be degraded in performance, because each call to getinstance () to lock the object. In fact. Just lock the first time you create the object, and it won't be necessary to create it later. So we can make further improvements. For example, the following:

public static Singleton getinstance () {          if (instance = = null) {              synchronized (instance) {                  if (instance = = NULL {                      instance = new Singleton ();          }}} return instance;  }
we add Synchronizedkeyword to the inside, that is, when the call is not required to lock, only when the instance = = NULL and create the object when the lock, this is better than the way above. However, this approach is likely to cause thread safety problems, since the creation of objects and assignment operations in the JVM is performed separately, that is, instance = new Singleton () is a two-step sentence. The process is this: the JVM allocates a blank memory to the singleton instance first. and assigned to the instance member, but at this point the JVM does not start initializing the instance. Then go to new a singleton object to assign to instance. This can cause threading problems. For example, a thread enters the synchronized code block and exits the code block after running instance = new Singleton (). However, there is no real initialization at this point, this is thread B coming in and discovering that instance is not NULL. The instance is then returned immediately (in fact not initialized), then B begins to use the instance, but finds no initialization, so there is a problem.

So to solve this "lazy" single-threaded problem, a proposal to use the above procedure in Listing 1, that is, the use of "a Hungry Man-type" single case. Also, in practice, an internal class can be used to maintain a singleton implementation. The mechanism inside the JVM guarantees that when a class is loaded. The onboarding process for this class is a thread that is mutually exclusive.

Such When we first called the getinstance () method. The JVM can help us ensure that the instance instance is created only once and that the memory that is assigned to instance is initialized to completion. See for example the following code:

/****************** Singleton mode: Program Listing 2 ****************************/public class Singleton {    private Singleton () {  // Private constructor method to prevent instantiation}/        * Use an inner class to maintain a singleton */      private static class Singletonfactory {          private static Singleton Instance = new Singleton ();      }        public static Singleton getinstance () {  //Get instance        return singletonfactory.instance;      }        /* Assume that the object is used for serialization. Ensures that objects are consistent before and after serialization *      /public Object Readresolve () {          return getinstance ();      }   } /********************************************************************/

3. Cloning of a singleton pattern

The above analysis of the single-instance mode of thread safety problem, there is a problem is to consider the single-mode object replication problem.

In Java. Objects cannot be copied by default, but if the Cloneable interface is implemented. and implements the Clone method, then can create a new object directly through the object copy way, the object copy is not the calling class construction method, so even the private construction method, the object can still be copied.

However, in the ordinary case, the Singleton class is rarely active request to be copied, so the best way to solve this problem is the Singleton class do not implement the Cloneable interface.

4. Expansion of Singleton mode

It is easy to assume that a class can produce multiple objects and that the number is unrestricted, and that it is straightforward to new.

But suppose a singleton pattern is used, but does it require a class to actually produce two or three objects? How can such a situation be achieved? In this case, we need to maintain a variable in the Singleton class to represent the number of instances. It also requires containers to hold different instances and the corresponding attributes of the instance, such as the following:

/*************************** single-instance mode extension: Listing 3 ************************************/public class Singleton {// Defines the maximum number of instances that can be generated private static int maxnumofinstance = 3;//stores the name of each instance private static arraylist<string> NameList = new ARR Aylist<string> ();//Store Each instance object private static arraylist<singleton> instancelist = new arraylist< Singleton> ();//index of the current instance private static int indexofinstance = 0;//static code block, initialize 2 instance static {for (int i = 0; i < maxnum) when class loads Ofinstance; i++) {Instancelist.add (New Singleton ("instance" + (i+1)));}} Private Singleton () {}private Singleton (String name) {//with a reference to the privately constructed constructor Namelist.add (name);} Return instance object public static Singleton getinstance () {Random random = new random ();//Randomly pick an instance indexofinstance = Random.nextint ( maxnumofinstance); return Instancelist.get (indexofinstance);} public void Test () {System.out.println (Namelist.get (indexofinstance));}}  /******************************************************************************************/
let's write a test procedure and see the results:

public class Singletontest {public static void main (string[] args) {int num = 5;for (int i = 0; i < num; i++) {Singleton Instance = Singleton.getinstance (); Instance.test ();}}}
This allows us to create a fixed number of instances using a singleton pattern. test results output such as the following:

Instance1instance1instance2instance3instance3

5. Advantages and disadvantages of singleton mode

Strengths:

1. There is only one instance in memory. Reduce the cost of the village altogether. In particular, an object needs to be created and destroyed frequently, and performance cannot be optimized when it is created or destroyed. The advantages of a singleton pattern are obvious.

2. Reduce the performance cost of the system. When an object is produced with more resources, such as reading a configuration and generating a dependent object, it is possible to produce a singleton object directly when the application starts. It is then permanently homed in memory.

3. The ability to avoid multiple uses of resources, such as writing file actions. Because only one instance exists in memory, avoid writing to the same resource file at the same time.

4. The singleton mode can set the global access point in the system. Optimize and share resource access, such as being able to design a singleton class that is responsible for mapping all data tables.

Disadvantages:

1. The singleton mode does not have an interface. Extension is very difficult. To extend, there is basically no other way to do this than to change the code to achieve

2. The singleton mode is unfavorable to the test, in the parallel development environment, it is not possible to test the singleton mode if it is not finished.

6. Application Scenarios for Singleton mode

In a system that requires a single class to have only one object, a singleton pattern can be used:

1. An environment that requires a unique serial number to be generated.

2. The entire project requires a shared access point or shared data, such as the number of visits on a Web page, and the ability to save records to the database without each refresh. However, ensure that the singleton thread is safe.

3. Creating an object requires too many resources to consume. To access resources such as IO and databases.

4. You need to define a large number of static constants and static methods (such as tool classes) of the environment. Can be used in a single case mode. Of course, it can be declared as a static method directly.

The singleton pattern is also used in spring, with each bean being a singleton by default, so the spring container can manage the lifetime of these beans, decide when to create them, when to destroy them, how to deal with them when they are destroyed, and so on.

Assuming that a non-singleton pattern (prototype type) is used, the management of the bean's initialization is given to the Java EE container, and the spring container is not tracking the lifetime of the bean.

The singleton mode is discussed so much, if there are errors, please leave a message ~

Related reading: http://blog.csdn.net/column/details/des-pattern.html

___________________________________________________________________________________________________________ __________________________________________

-----willing to share and progress together!

-----Many other articles please see: http://blog.csdn.net/eson_15

Java design mode singleton (Singleton) mode

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.