Singleton mode, Mode

Source: Internet
Author: User

Singleton mode, Mode
1. Advantages and Disadvantages

The standalone Mode means that only one instance can exist in one jvm (reflection is not considered). This design has two advantages:

1. for jvm, for frequently-used objects, the creation time can be subtracted (this is a very objective overhead for heavyweight objects), because operations on new objects are reduced, reducing the usage frequency of the system memory will reduce the GC pressure and shorten the GC pause time (from java program performance optimization-ge yiming ).

2. In terms of design, some instances should have only one (logically) system, and only operate on the same object, which can effectively ensure consistency (can be processed in concurrency ).

There are also some issues that need attention:

1. Because there is no abstract layer in the single-profit mode and it is not conducive to expansion, many of the responsibilities are borne by themselves, which may lead to excessive responsibilities of the single-instance class, to some extent, it violates the "single responsibility principle ".

2. If the instance creation process is slow and may not be used, loading may be delayed.

3. Misuse of Singleton may cause some negative problems. For example, designing database connection pool objects as Singleton classes to save resources may lead to excessive programs sharing connection pool objects and connection pool overflow; if the instantiated object is not used for a long time, the system will regard it as garbage and be recycled, which will lead to the loss of the object state.

2. Implementation Method

The root implementation of a singleton is the privatization Constructor (creating objects within the class), and then designing methods to obtain instances based on different scenarios. Below are several common implementation methods.

1. Hungry Chinese Style: This method completes initialization during class loading, so the class loading is slow, but the object retrieval speed is fast. Implementation based on the class loading mechanism can avoid the synchronization of multiple threads, but it cannot be determined that other methods (or other static methods) cause class loading, at this time, the initialization of the instance obviously does not achieve the effect of delayed loading.

1 public class Singleton1 {// Chinese Style 2 private Singleton1 () {} 3 private static Singleton1 singleton = new Singleton1 (); 4 public static Singleton1 getInstance () {5 return singleton; 6} 7}

2. Lazy: latency loading is possible, but there is a fatal problem in multithreading.


1 public class Singleton2 {// lazy 2 private Singleton2 () {}; 3 private static Singleton2 singleton; 4 public static Singleton2 getInstance () {5 if (singleton = null) {6 singleton = new Singleton2 (); 7} 8 return singleton; 9} 10}

3. Double check mode: improved lazy mode. To solve the thread synchronization problem, the simplest method is to add the keyword synchronized to the getInstance method as a whole, but the efficiency of this implementation method will be at least two orders of magnitude lower. One of the good ways to improve isDouble Check Mode(DCL), this method is used to empty singleton twice in the getSingleton method. The first is for unnecessary synchronization, and the second is to create an instance when singleton is null. The volatile keyword is used here. Using volatile will affect the performance more or less. However, considering the correctness of the program, it is worthwhile to sacrifice this performance. DCL has the advantage of high resource utilization. When getInstance is executed for the first time, the single-instance object is instantiated, which is highly efficient. The disadvantage is that the response is a little slower during the first loading, and there are also some defects in the high concurrency environment (DCL failure), although the probability of occurrence is very small.

1 public class Singleton3 {// Dual Check Mode (DCL) 2 private Singleton3 () {}; 3 private static volatile Singleton3 singleton; 4 public static Singleton3 getInstance () {5 if (singleton = null) {6 synchronized (Singleton3.class) {7 if (singleton = null) {8 singleton = new Singleton3 (); 9} 10} 11} 12 return singleton; 13} 14}

4. static internal class: both delayed loading and no thread problems (Recommendation)

1 public class Singleton4 {// static internal class mode (DCL) 2 private Singleton4 () {}; 3 static class ClassHolder {4 private static Singleton4 singleton = new Singleton4 (); 5} 6 public static Singleton4 getInstance () {7 return ClassHolder. singleton; 8} 9}

5. enumeration: This method is advocated by Josh Bloch, the author of objective java. It not only avoids multi-thread synchronization, but also prevents deserialization and re-creation of objects. It sounds awesome, but I have never seen it at work. I have a chance to try it.

1 public enum Singleton5 {// enumeration Mode 2 INSTANCE; 3 public void whateverMethod () {4 // used in the same enumeration class (it was originally an enumeration !), You do not need to obtain an instance. 5} 6}

6. use container to ensure singleton: This method can effectively manage multiple types of Singleton without considering the container's concurrent processing, in addition, a unified interface can be used to obtain data, which reduces the user's usage cost and hides the specific implementation from the user, reducing the coupling degree.

1 // use the container to implement Singleton 2 // it is best to privatize the singleton object constructor you want to load, this can avoid many problems. 3 // if you can ensure that the object is retrieved from this class loader every time, whether the constructor is privatized is irrelevant. 4 public class SingletonManager {5 private static Map <String, object> objMap = new HashMap <String, Object> (); 6 public static void registerService (String key, Object instance) {7 if (! ObjMap. containsKey (key) {8 objMap. put (key, instance); 9} 10} 11 public static Object ObjectGetService (String key) {12 return objMap. get (key); 13} 14}
3. Destruction of Singleton

1. Reflection: if he does not exist, right.

2. multiple class loaders: for example, some servlet containers use different class loaders for each servlet. In this case, if two servlets access a single class, they all have their own instances. The solution is to use the same class loader (nonsense ).

3. serialization and Restoration: When you serialize and restore a singleton object, multiple Singleton objects will appear. For example:

1 public class Test {2 public static void main (String [] args) throws IOException, ClassNotFoundException {3 Singleton1 singleton = Singleton1.getInstance (); 4 // serialize the singleton object to the file 5 FileOutputStream outputStream = new FileOutputStream ("E: Singleton.txt"); 6 ObjectOutputStream objectOutputStream = new ObjectOutputStream (outputStream); 7 objectOutputStream. writeObject (singleton); 8 objectOutputStream. flush (); 9 objectOutputStream. close (); 10 // read object from file 11 FileInputStream inputStream = new FileInputStream ("E: Singleton.txt"); 12 ObjectInputStream objectInputStream = new ObjectInputStream (inputStream ); 13 Singleton1 newSingleton = (Singleton1) objectInputStream. readObject (); 14 15 // test16 System. out. println (singleton = newSingleton); // false17 System. out. println (singleton = Singleton1.getInstance (); // true18} 19 20}

An effective method is to add the readResolve Method to the singleton class (the serialization operation provides a very special hook class with a private instantiated method readresolve (), this method ensures that class developers have a say in what object will be returned by serialization ). For example:

1 public class Singleton1 implements Serializable {// Chinese Style 2 private Singleton1 () {} 3 private static Singleton1 singleton = new Singleton1 (); 4 public static Singleton1 getInstance () {5 return singleton; 6} 7 private Object readResolve () {8 return singleton; 9} 10}

The test above will contain two true values.

4. Thanks! A lot of content is retrieved from the Internet. Thank you !!

 

 

  

 

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.