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 > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you what are the ways to achieve the Java singleton pattern, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Why do you use singleton mode?
You need to make sure that a class needs only one object, or that creating a class consumes too many resources, such as accessing IO and database operations, and so on, so you need to consider using singleton patterns.
Key points to pay attention to when using singleton mode
Set the constructor access modifier to private
Returns a singleton class object through a static method or enumeration
Make sure there is only one object for the singleton class, especially in a multithreaded environment
Ensure that singleton class objects are not rebuilt when deserialized
Several writing methods of singleton pattern 1. Realize the singleton mode * / public class Singleton {private static Singleton instance = new Singleton (); private Singleton () {} public static Singleton getInstance () {return instance;} 2. Lazy / * * lazy implement singleton mode * / public class Singleton {private static Singleton instance; private Singleton () {} / / synchronized method to ensure singleton object unique public static synchronized Singleton getInstance () {if (instance = = null) {instance = new Singleton ();} return instance;}} in the case of multithreading
The synchronized keyword has been added to the getInstance () method to make it a synchronous method in order to ensure that the singleton object is unique in a multithreaded environment.
Advantages: singletons are instantiated only when in use, saving resources to a certain extent.
Disadvantages: instantiate immediately when you load for the first time, and react a little slowly. Each call to the getInstance () method synchronizes, which consumes unnecessary resources. This mode is generally not recommended.
3. DCL (Double CheckLock) implement singleton / * DCL implement singleton mode * / public class Singleton {private static Singleton instance = null Private Singleton () {} public static Singleton getInstance () {/ / two layers are null, the first layer is to avoid unnecessary synchronization / / the second layer is to create an instance if (instance = = null) {synchronized (Singleton.class) {if (instance = = null) {instance = new Singleton () in the case of null } return instance;}}
Advantages: high resource utilization, can not only initialize the instance when needed, but also ensure thread safety, while calling the getInstance () method without synchronous locking, high efficiency.
Cons: the first load is a little slow and occasionally fails due to the Java memory model. There are also some defects in the high concurrency environment, although the occurrence probability is very small.
The DCL pattern is the most frequently used singleton pattern implementation, which can basically meet the requirements unless the code is complex in concurrent scenarios or is used in versions below JDK 6.
4. Static inner class / * * static inner class implements singleton mode * / public class Singleton {private Singleton () {} public static Singleton getInstance () {return SingletonHolder.instance;} / * static inner class * / private static class SingletonHolder {private static Singleton instance = new Singleton ();}}
The instance is not initialized the first time the Singleton class is loaded, only when the getInstance () method is called for the first time, the virtual machine loads the SingletonHolder class and initializes the instance.
This method not only ensures thread safety, the singleton object is unique, but also delays the initialization of the singleton. It is recommended to use this way to implement the singleton pattern.
5. Enumerate singletons / * enumeration to implement singleton pattern * / public enum SingletonEnum {INSTANCE; public void doSomething () {System.out.println ("do something");}}
The creation of the default enumerated instance is thread-safe, and even deserialization does not generate a new instance, which is a singleton in any case.
Pros: simple!
6. Container implements singleton import java.util.HashMap;import java.util.Map;/** * Container class implements singleton pattern * / public class SingletonManager {private static Map objMap = new HashMap (); public static void regsiterService (String key, Object instance) {if (! objMap.containsKey (key)) {objMap.put (key, instance);}} public static Object getService (String key) {return objMap.get (key) }}
SingletonManager can manage multiple singleton types and obtain objects of the corresponding type according to key when using it. In this way, the operation can be obtained through a unified interface, hiding the specific implementation and reducing the degree of coupling.
These are all the contents of the article "what are the ways to implement the Java singleton pattern?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to 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.