In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)06/01 Report--
Speaking of singleton pattern, we may be familiar with it, and it can be said that the design pattern appears most frequently. In order to thoroughly understand the singleton, I will explain what the singleton is, the evolution of the singleton pattern, and the difference between the singleton pattern and the static class.
1: concept
What is a singleton is that there can be only one instance in an application, which ensures that the object can only be new once.
2: lazy mode
Lazy man, I think the name is very vivid, that is, it is very lazy, so when other objects are loaded, it does not load. I was loading when you called me. Metaphorically, there is also a lazy mode in hibernate. Ok, let's get started.
2.1: non-thread safe
One day when Xiaoming went to the interview, the interviewer said, please write me a singleton model. Xiaoming thought it was too easy to think about it and soon wrote the following singleton pattern.
1 public class Singleton {2 private static Singleton singleton; 3 public static Singleton getSingleton () 4 {5 if (singleton==null) 6 {7 singleton=new Singleton (); 8} 9 return singleton;10} 11}
Then the interviewer looked at it and said, "you may have multiple singleton instances at a high concurrency. Xiao Ming thought how could it happen?" the interviewer explained that if two threads T1 and T2 execute at the same time, when T1 executes to line 6, the time frame arrives, and the system starts to let T2 execute, execute to line 9, and then T1 starts to execute again, because T1 has already made a judgment and does not know that singleton has been instantiated. So singleton is instantiated again at this time, so your system has two singleton objects. Is that still a singleton? Xiao Ming suddenly realized that I could solve this, and immediately wrote the following one.
2.2: thread safety
1 public class Singleton {2 private static Singleton singleton; 3 4 public synchronized static Singleton getSingleton () 5 {6 if (singleton==null) 7 {8 singleton=new Singleton (); 9} 10 return singleton;11}
As soon as the interviewer looked, adding thread synchronization, it did guarantee thread safety at this time, but he also raised questions. If singleton has been instantiated now, if 10 threads visit at the same time, it is bound to cause great performance consumption every time. Do you have any other solutions to solve the problem? Xiaoming wrote down the following code after a minute of thinking.
2.3: double check
1 public class Singleton {2 private static Singleton singleton; 3 4 public static Singleton getSingleton () 5 {6 if (singleton==null) 7 {8 synchronized (Singleton.class) {9 if (singleton==null) 10 {11 singleton=new Singleton (); 12} 13} 14} 15 return singleton 16}
The interviewer saw that it really improved a lot of performance and reduced unnecessary waiting on the basis of the above code, but after a careful look, he said that there was something wrong with your code and could not guarantee thread safety. What did Xiao Ming say? then the interviewer explained: if there are two threads, T1 thread T2, and T1 thread runs line 6 to find singleton==null, go to line 8 and start instantiating singleton, because the instantiation is divided into three steps. The first step is to open up memory space for the object, the second step is to initialize the object, and the third step is to assign this memory address to singleton, but because the memory mode of java allows unordered writes, this will lead to the position exchange between the second step and the third step, so it will be bad. If the first and third steps are allowed first, but the object is not initialized at this time, T2 enters line 6. If it is determined that singleton is not null, an object that has not been initialized will be returned. Xiaoming thought it was right when he heard this. He said that I just changed the memory mode to not allow unordered writing, so I changed the code to
1 public class Singleton {2 private volatile static Singleton singleton;// means writing 3 4 public static Singleton getSingleton () 5 {6 if (singleton==null) 7 {8 synchronized (Singleton.class) {9 if (singleton==null) 10 {11 singleton=new Singleton () 12} 13} 14} 15 return singleton;16}
Note 1: in the three steps of object instantiation, I will make an analogy here. A company allocates a dormitory to its employees (which means opening up space in the heap) and then gives some standard metaphors to the house, such as air conditioners, washing machines and so on (object initialization). Then, give the key to the employee (object assignment).
3: hungry man model
The interviewer asked you again if you know how to write the hungry man model. Xiao Ming listened: Oh, hungry man, I was just in a hurry to instantiate myself immediately, for fear that I could not instantiate it. I wrote a hungry man right away.
Public class Singleton {private static Singleton singleton=new Singleton (); public static Singleton getSingleton () {return singleton;}}
The interviewer looks really good.
4: inner class mode
As soon as Xiao Ming looked at the above mode, he had a whim. The hungry mode was anxious to create objects and consumed performance when loading, while the lazy mode had thread safety problems (no more after optimization). Can you combine it? suddenly told the interviewer that I had a better way to do it, and then he wrote the following code
1 public class Singleton {2 private static class SingletonManager {3 private final static Singleton SINGLETON=new Singleton (); 4} 5 public final static Singleton getSingleton () 6 {7 return SingletonManager.SINGLETON;8}
As soon as the interviewer looked, it was good, not only ensuring lazy loading, but also ensuring thread safety issues.
5: use the scene
The interviewer asked Xiao Ming, do you know the use scenario? Xiao Ming thought about it and said that since there is only one singleton in the application, it is bound to be used to share resources, for example, database connection pool, thread pool and so on.
6: the difference between singleton mode and static class
The interviewer continued to ask: the static class also produces an object, which is highly similar to the singleton. Do you know the difference between them? Xiaoming replied.
1: there are three major characteristics of object-oriented inheritance, encapsulation and polymorphism, but static classes cannot be inherited, so static classes do not conform to object-oriented from the point of view of oo, and their classes cannot be overridden, so their flexibility is much less than that of singletons.
2: because of the special nature of static classes, he has instantiated them in the compiler and cannot provide lazy loading mode.
3: for the unit test in the project, it is also difficult for the test because the method cannot be covered.
4: since static classes have been instantiated in the compiler, they are faster than singletons. If you only need to execute some static methods, you can use static classes.
7: summary
The singleton model seems simple, but in fact, there are many problems to be considered when it is used. Now I have basically summarized this process. Of course, there may be inadequacies. Welcome to correct.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.