In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "how to define the java singleton pattern". Many people will encounter such a dilemma in the operation of the actual case, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Singleton pattern definition:
The singleton pattern ensures that there is only one instance of a class and instantiates itself and provides that instance to the entire system. In computer systems, driver objects for thread pools, caches, log objects, dialogs, printers and graphics cards are often designed as singletons. These applications all have the function of resource manager more or less. Each computer can have several printers, but only one Printer Spooler to prevent two print jobs from being output to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to prevent one communication port from being called by two requests at the same time. In short, the singleton mode is chosen to avoid inconsistencies and long positions.
1. Classic hungry Han style:
Public class Singleton {
Private final static Singleton INSTANCE = new Singleton ()
Private Singleton () {}
Public static Singleton getInstance () {
Return INSTANCE
}
}
Features: when the program starts to load, first load the class, and then initialize the static properties, because the object can not be modified later, so as to achieve thread safety, the efficiency is relatively high. It takes up a lot of memory.
Disadvantages: if this class is particularly large, initialization will be very slow, and if we do not use this class, it will still be created, a waste of resources.
2. Classic lazy style:
Public class Singleton {
Private static Singleton singleton
Private Singleton () {}
Public static synchronized Singleton getInstance () {
If (singleton = = null) {
Singleton = new Singleton ()
}
Return singleton
}
}
Features: delayed loading, saving memory. The efficiency is relatively low. Use synchronization blocks to achieve thread safety.
Cons: the synchronized keyword is a relock (object lock) that locks the object every time it calls getInstance (). In fact, it needs to be locked only when the object is created for the first time, but not later.
3. Lazy variant-double check structure (without volatile keyword modification):
Package cn.hzy.creationPattern.singleton
Public class Singleton3 {
Private static Singleton3 instance = null
Private Singleton3 () {
}
Public static Singleton3 getInstance () {
If (instance = = null) {
Synchronized (instance) {
If (instance = = null) {
Instance = new Singleton3 ()
}
}
}
Return instance
}
}
Features: it belongs to a lazy variant, with all the above lazy features, but the performance problem is optimized here. Instead of adding a lock to the getInstance () method, it only gives instance = new Singleton3 (); lock, that is, it will only be locked during initialization, and the subsequent access will not be locked because of instancelazy null.
Disadvantages: at first glance, this mode has no thread safety problems and ensures singletons, which seems perfect, but it is possible for JVM to rearrange instructions to optimize performance when creating objects.
The seemingly simple sentence instance = new Singleton3 (); JVM has three steps when creating an object:
1. Allocate a memory space to Singleton3
2. Initialize Singleton3 (that is, create a Singleton3 object)
3. Point the instance to the address of the memory space you just allocated
But it is possible that JVM may become the following order in order to improve efficiency for compilation optimization:
1. Allocate a memory space to Singleton3
2. Point the instance to the address of the memory space you just allocated
3. Initialize Singleton3 (that is, create a Singleton3 object)
In fact, this situation has no effect in the single-threaded case, and the result is the same, but in the multithreaded case, it may lead to an error.
For example, two threads An and B access the getInstance () method. A first enters the first if judgment, and then enters the synchronized block to initialize the Singleton3. Due to the instruction rearrangement, the instance is pointed to the newly allocated memory space address (no Singleton3 object is created at this time). At this time, B accesses the getInstance () method, and B enters the first if judgment, because instance already points to an existing memory space address, that is, instancememory space null. Return instance (uninitialized) directly at this time, and then if An is not initialized, a null pointer error will be reported. (very low probability)
Solution: add volatile keyword modification
Volatile:
Feature 1: memory visibility, that is, thread A's modification of the volatile variable, and the volatile variables obtained by other threads are up-to-date.
Feature 2: instruction reordering can be disabled.
Modify it as follows: change private static Singleton3 instance = null; to private static volatile Singleton3 instance = null
4. Static inner class:
Package cn.hzy.creationPattern.singleton
Public class Singleton4 {
Private Singleton4 () {}
Public static Singleton4 getInstance () {
Return SingletonFactory.instance
}
Private static class SingletonFactory {
Private static Singleton4 instance = new Singleton4 ()
}
}
Features: it also belongs to lazy mode by feature, because instance objects are created only when we need to use them. Here, we privatize the constructor and use internal classes to maintain the singleton implementation, because the internal mechanism of JVM ensures that when a class is loaded, the loading process of this class is thread mutually exclusive. In this way, when we call getInstance for the first time, JVM can ensure that the instance is created only once and that the memory assigned to instance is initialized, so that we don't have to worry about the problems with Singleton3. At the same time, this method only uses the mutex mechanism when it is called for the first time, which solves the problem of low performance.
Disadvantages: this seems to be perfect, but the static inner class also has a fatal disadvantage, that is, the problem of passing parameters. Because it is in the form of a static internal class to create a singleton, the external cannot pass parameters into it.
5. Enumerate:
Public enum Singleton {
INSTANCE
Public void method () {
}
}
Calling SingleTon.INSTANCE directly is a singleton.
Features: creating enumerations is thread-safe by default
Advantages: simply not too much, 1, the writing method is simple, compared with the above examples can be found. 2. It can prevent reflection attack.
Let me say a little bit about the above reflection attack: in the above 1, 2, 3, and 4 singleton modes, if we don't do some security handling on the constructor, we can easily get the constructor through reflection and create more than one instance object, which is no longer a singleton. But for enumerations, even if you get the constructor through reflection, you will also report an error when creating an object instance, because enumerations can prevent reflection attacks.
How to do some security handling on the constructor?
You can set up a flag, after creating an object instance, change the value of flag, and throw an exception through judgment.
For example:
Private static boolean flag = false
Private Singleton () {
Synchronized (Singleton .class) {
If (false = = flag) {
Flag =! flag
} else {
Throw new RuntimeException ("Singleton mode is being attacked by reflection!")
}
}
}
It is guaranteed not to be attacked by reflection by adding a judgment to the constructor.
This is the end of the content of "how to define the java singleton pattern". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.