Notes on design mode 01: simple and efficient single example mode

Design patterns are essential skills for good programmers, and they are often mentioned in interviews.

  • Preface

    IT industry is the industry with high job hopping rate, which is not frequent to interview. As an interviewer, if the candidate's other knowledge is OK, I will finally mention the content related to * * design pattern. If the answer is not clear, I will tell him to do the project. If the answer is good, it will be directly arranged to the product group.

  • Effect

    It ensures that there is only one object instance of this class in the system memory, saving system resources. Improve system performance for objects requiring frequent creation and destruction

  • scene

    Objects that need to be created and destroyed frequently. Objects that take too much time or consume too much resources but are often used.

  • start

    Singleton pattern is a simple design pattern. Most programmers are familiar with the singleton pattern (when I first started, I didn't insist on learning all 23 design patterns for many times, resulting in the result that the singleton pattern has been repeated many times [doghead]).

    There are 8 single mode in the industry. In fact, you don't need to learn all of these kinds. You can focus on three kinds of thread safety. (for others, don't study any more, artificially increase the difficulty).

    1. duplication check

      public class Singleton {
      
       // Private constructor, which is created directly through new
       private Singleton() {}
      
       // Provide global instance object, receive creation value (lazy load)
       private static volatile Singleton instance;
      
       // Provides a way to get an instance
       public static Singleton getInstance() {
      
           //Key 1: judge whether the current instance is null by instance == null. If it is not equal to null, return the value directly
           if (instance == null) {
               //Key 2: control thread safety through synchronized keyword
               synchronized (Singleton.class) {
                   //Key 3: only one thread is executing in synchronized. At this time, judge whether to create or not according to whether the object is null.
                   if (instance == null) {
                       instance = new Singleton();
                   }
               }
           }
           return instance;
       }
      
      public void method(){}
      }
      • Question 1: why should instance judge whether it = = null twice?
      synchronized (Singleton.class) {           
       if (instance == null) {
         instance = new Singleton();
       }
      }
      //1. instance == null in synchronized prevents instance from being created repeatedly. For example, when two threads a and B. A enter synchronized, B may also wait outside synchronized. After a thread creates an instance successfully, B enters the thread again. At this time, B can be controlled to use it directly according to the instance == null in synchronized to prevent re creation.
      //2. instance == null outside synchronized controls efficiency. If the instance object already exists at this time, another thread C will return directly without executing the synchronized part of the code. Improve the efficiency of implementation. (we all know that synchronized is slow [dog head])
      • Question 2: what is volatile?

      volatile is a big topic, involving memory model.

      Simply put: volatile allows variables to be taken from main memory every time they are used. Instead of "working memory" from individual threads.

    2. Static inner class

      A single example implemented by static inner class loading mechanism

      public class Singleton {
      
       private Singleton() {}
      
       //1. Static internal class mechanism: when Singleton is loaded, SingletonInstance class will not be loaded immediately. The function of lazy loading is realized
       //2. When SingletonInstance.INSTANCE is called, it will be loaded immediately, and it is thread safe.
       public static class SingletonInstance {
           private static final Singleton INSTANCE = new Singleton();
       }
       // Provides a way to get an instance
       public static Singleton getInstance() {
           return SingletonInstance.INSTANCE;
       }
      
       public void method(){}
      }
    3. enumeration

      It is recommended to use the enumeration mechanism to implement a single example. It can not only avoid multithreading synchronization, but also prevent deserialization from re creating new objects.

      public enum Singleton {
       INSTANCE;
       public void method(){}
      }
      • Question 1: what is public void method() {}?

      I also met this problem at the beginning of my study. I understand it naturally, and I am confused about what I don't understand. Searching for information on the Internet is exactly the same.

      The answer is simple, in a word. The singleton mode is used to create a unique instance. So what do you do with this instance after it's created? Yes, naturally it's the method of the class it's in. public void method() {} is the method you want to call.

      In other tutorials, double checking and static inner classes only write to get instances, not public void method() {}, which causes confusion. Careful children's shoes may have noticed that I have written public void method() {} for all three singleton modes. Hurry up to praise me for my carefulness.

      Finally, warm reminder, enumeration is the most simple, but also recommended method, quickly practice a few times, the interview seconds kill the interviewer!

  • The application of single case in jdk

    java.lang.Runtime
    
    public class Runtime {
      private static Runtime currentRuntime = new Runtime();
    
      /**
       * Returns the runtime object associated with the current Java application.
       * Most of the methods of class <code>Runtime</code> are instance
       * methods and must be invoked with respect to the current runtime object.
       *
       * @return  the <code>Runtime</code> object associated with the current
       *          Java application.
       */
      public static Runtime getRuntime() {
          return currentRuntime;
      }
    
      /** Don't let anyone else instantiate this class */
      private Runtime() {}
    
    }
  • Other applications

    Data source, session factory, etc

Tags: Java JDK Session

Posted on Wed, 12 Feb 2020 20:21:37 -0800 by auddog