In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about how to analyze the Java singleton design pattern, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Characteristics of singleton model
1. The constructor is private
2. In a Java application, only one instance object can be guaranteed.
3. Only one getInstance () method is provided for external calls
Advantages of singleton mode
1. Reduce the frequent creation of some objects, reduce system overhead and memory footprint.
2. External calls do not use the new keyword, which reduces the frequency of using system memory.
3. For special classes, only one instance can exist in the system, otherwise the system will not work properly, such as Controller
Mode of realization
Two implementation methods are briefly introduced here.
Hungry Chinese (thread safety) / * * @ author: xuzhilei6656 * @ create: 2021-12-12 12:07 * @ description: singleton mode (hungry Chinese) * * / public class Singleton {/ / create instance private static Singleton instance = new Singleton (); / / Private constructor private Singleton () {} / / static method to get the instance public static Singleton getInstance () {return instance;}}
The instance object is initialized when the class is loaded, and all the external calls get is the only instance object.
Lazy author / * * @ author: xuzhilei6656 * @ create: 2021-12-12 12:22 * @ description: singleton mode (lazy) * * / public class Singleton {/ / declare a variable private static Singleton instance / / Private constructor private Singleton () {} / / gets the static method public static Singleton getInstance () of the instance {/ / if it is called for the first time and the instance object has not been created, it needs to be created, otherwise it will return the created object if (instance = = null) {instance = new Singleton ();} return instance;}}
Compared with the hungry Chinese style, the instance object is not created when the class is loaded, it is created when it is first called, and then called later, and the only instance object is returned.
In the case of multithreading, this method has thread safety problems. For example, thread An enters a blocking state after executing the if judgment condition, and no object creation is carried out at this time. Thread B comes and creates the object directly after executing the if condition, and after thread A resumes the running state, the object creation will also be carried out. At this time, it does not conform to the singleton mode, that is, the problem of thread unsafety occurs.
Solution: add the synchronized keyword to the static method of getting the instance, that is, lock
/ * * @ author: xuzhilei6656 * @ create: 2021-12-12 12:22 * @ description: singleton mode (lazy) * * / public class Singleton {/ / declare a variable private static Singleton instance / / Private constructor private Singleton () {} / / gets the static method public static synchronized Singleton getInstance () of the instance {/ / if it is called for the first time and the instance object has not been created, it needs to be created, otherwise it will return the created object if (instance = = null) {instance = new Singleton ();} return instance;}}
Simple and rough, we can achieve our goal, but every time we get the instance object, there must be a locking operation, which affects the performance of the system.
Improved scheme: double check
/ * * @ author: xuzhilei6656 * @ create: 2021-12-12 12:22 * @ description: singleton mode (lazy) * * / public class Singleton {/ / declare a variable private static Singleton instance / / Private constructor private Singleton () {} / / static method public static synchronized Singleton getInstance () {/ / check if (instance==null) {/ / acquire lock synchronized (Singleton.class) {/ / check if (instance==null) {for the second time / / both checks confirm that there are no existing instance objects This is the only way to create the object instance = new Singleton () } return instance;}}
In this way, it is not necessary to lock the instance object every time, but only when the object is created for the first time, which improves the performance of the system.
But even so, it may happen. Because instance = new Singleton () is two operations in JVM, assigning and initializing instances, but JVM does not guarantee the order of these two operations. It is possible that JVM allocates space to new objects and assigns values directly to instance variables before initializing the instance. For example, in the following situation
Both threads enter the first if condition
2. Thread A first grabs the lock and enters the synchronized code block, executes the line of code instance = new Singleton (), and then releases the lock. At this time, it is possible that JVM only allocates blank memory space to the instance object and does not perform initialization operations.
3Jing B thread grabs the lock, enters the synchronized code block, finds that instance is not null when judging for the second time, and returns directly to use but finds that the resulting object has not been initialized, so there is a problem.
Improve again: use the volatile keyword to modify the declared member variable instance
/ * * @ author: xuzhilei6656 * @ create: 2021-12-12 12:22 * @ description: singleton pattern (lazy) * / public class Singleton {/ / declare variables, decorated with private volatile static Singleton instance by volatile / / Private constructor private Singleton () {} / / static method public static synchronized Singleton getInstance () {/ / check if (instance==null) {/ / acquire lock synchronized (Singleton.class) {/ / check if (instance==null) {for the second time / / both checks confirm that there are no existing instance objects This is the only way to create the object instance = new Singleton () } return instance;}}
Volatile keyword function: variables modified by volatile will not be cached locally by the thread, and all threads' reading and writing to the object will be synchronized to the main memory at the first time, thus ensuring the accuracy of the object among multiple threads.
This method of writing is perfect, which can not only ensure the safe creation of a unique instance, but also will not have too much impact on the system performance.
However, there is a better way to write it: static inner class implementation
/ * * @ author: xuzhilei6656 * @ create: 2021-12-12 15:17 * @ description: singleton mode * * / public class Singleton {/ / Private constructor private Singleton () {} / / static inner class declaration instance private static class SingletonFactory {private static Singleton instance = new Singleton ();} / get the static method public static Singleton getInstance () {return SingletonFactory.instance of the instance }}
Using inner classes to maintain singleton implementations, JVM's internal mechanism ensures that when a class is loaded, the loading process of that class is thread mutually exclusive. In this way, when we call the getInstance () method for the first time, JVM can guarantee that a unique instance object is created, and the instance object has been initialized, which solves the above thread safety problem.
The last way to realize the singleton is also perfect, and the code is the most concise.
By enumerating
/ * * @ author: xuzhilei6656 * @ create: 2021-12-12 15:33 * @ description: singleton mode * * / public enum Singleton {/ / represents a Singleton instance INSTANCE;}
The implementation of single instance code through enumeration is more concise, and JVM fundamentally ensures the uniqueness of instance objects, which is a more concise, efficient and secure way to implement singletons.
The above is how to analyze the Java singleton design pattern, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.