In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to understand the Java singleton pattern". Many people will encounter such a dilemma in the operation of actual cases, 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!
I. introduction
Speaking of singleton pattern (Singleton Pattern), you must be familiar with, it is one of the simplest design patterns in Java, is a kind of creative pattern, it provides the best way to create objects.
The significance of this pattern is to ensure that there is only one instance of a class and to provide a global access point to access it, avoiding repeated creation of objects and saving system resources.
Second, the realization train of thought
Create a class, privatize its default constructor, make it impossible for outsiders to get the object instance through new Object, and provide a method to get the unique instance of the object.
For example, create a SingleObject as follows:
Public class SingleObject {/ / create an object of SingleObject private static SingleObject instance = new SingleObject (); / / make the constructor private so that the class will not be instantiated private SingleObject () {} / / to get the only available object public static SingleObject getInstance () {return instance;} public void showMessage () {System.out.println ("Hello World!");}}
Get a unique object from the singleton class
Public class SingletonPatternDemo {public static void main (String [] args) {/ / illegal constructor / / compile-time error: constructor SingleObject () is invisible / / SingleObject object = new SingleObject (); / / get the only available object SingleObject object = SingleObject.getInstance (); / / display message object.showMessage ();}}
Execute the program and output the result:
Hello World!
Third, several ways to realize the singleton model.
3.1. Lazy, thread unsafe (not recommended)
This is the most basic implementation, and the biggest problem with this implementation is that it does not support multithreading. Because synchronized is not locked, it is not strictly a singleton pattern. In this way, lazy loading is obvious, does not require thread safety, and does not work properly in multithreading.
Public class Singleton {private static Singleton instance; private Singleton () {} public static Singleton getInstance () {if (instance = = null) {instance = new Singleton ();} return instance;}}
3.2. Lazy, thread safe (not recommended)
This approach has a good lazy loading and works well in multithreading, but it is inefficient and does not require synchronization in 99% of the cases. Advantages: initialize only the first call to avoid memory waste. Disadvantages: synchronized must be locked to guarantee singletons, but locking will affect efficiency. The performance of getInstance () is not critical to the application (this method is used infrequently).
Public class Singleton {private static Singleton instance; private Singleton () {} public static synchronized Singleton getInstance () {if (instance = = null) {instance = new Singleton ();} return instance;}}
3.3. Hungry Han style (recommended)
This method is more commonly used, but it is easy to produce junk objects. Advantages: without locking, the execution efficiency will be improved. Disadvantages: initialize the class when it is loaded, wasting memory. It avoids the problem of multi-thread synchronization based on the classloader mechanism, but instance is instantiated when the class is loaded. Although there are many reasons for class loading, most of them call the getInstance method in the singleton mode, but it is not sure that there are other ways (or other static methods) that lead to class loading. At this time, initializing instance obviously does not achieve the effect of lazy loading.
Public class Singleton {private static Singleton instance = new Singleton (); private Singleton () {} public static Singleton getInstance () {return instance;}}
3.4. Double check lock / double check lock (recommended)
This approach uses a double-lock mechanism, which is safe and can maintain high performance in the case of multithreading. The performance of getInstance () is critical to the application.
Public class Singleton {private volatile static Singleton singleton; private Singleton () {} public static Singleton getSingleton () {if (singleton = = null) {synchronized (Singleton.class) {if (singleton = = null) {singleton = new Singleton () } return singleton;}}
3.5. Static inner class (recommended)
This method can achieve the same effect of double-check lock, using delayed initialization for static domain, but it is easier to implement. This method is only applicable to static domains, and double locking can be used when the instance domain needs to be deferred for initialization.
Public class Singleton {private static class SingletonHolder {private static final Singleton INSTANCE = new Singleton ();} private Singleton () {} public static final Singleton getInstance () {return SingletonHolder.INSTANCE;}}
3.6. Enumeration (recommended)
This implementation has not been widely adopted, but it is the best way to implement the singleton pattern. It is more concise, automatically supports serialization mechanisms, and absolutely prevents multiple instantiations. This approach is advocated by Effective Java author Josh Bloch, which not only avoids the problem of multithreaded synchronization, but also automatically supports serialization mechanisms to prevent deserialization from recreating new objects and absolutely prevent multiple instantiations. However, because the enum feature was added after JDK1.5, writing in this way is unfamiliar and rarely used in practice.
Public enum Singleton {INSTANCE; public void doMethod () {}}
IV. Application
Singleton mode is also widely used in Java. For example, Runtime is a typical example. The source code is as follows:
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 Runtime are instance * methods and must be invoked with respect to the current runtime object. * * @ return the Runtime object associated with the current * Java application. * / public static Runtime getRuntime () {return currentRuntime;} / * * Don't let anyone else instantiate this class * / private Runtime () {}...}
It is very clear to see that the hungry Han style is used to create a singleton object!
This is the end of "how to understand 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.