Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the singleton mode of Java

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to realize the singleton pattern of Java". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this article "how to realize the singleton pattern of Java" can help you solve the problem.

What is the singleton pattern?

Singleton pattern (Singleton Pattern) is a relatively simple pattern, which is widely used in practice. for example, the Bean instance in Spring is a singleton object.

Definition: make sure that there is only one instance of a class and instantiate it itself and provide this instance to the entire system.

Advantages and disadvantages of singleton model

Advantages

There is only one instance, which reduces memory overhead, especially the frequent creation and destruction of instances.

Singleton mode can avoid multiple occupation of resources, such as a write file action, because only one instance exists in memory, avoiding writing to the same resource file at the same time.

The singleton pattern can set global access points in the system, optimize and share resource access, for example, you can design a singleton class that is responsible for mapping all data tables.

Shortcoming

The singleton pattern generally has no interface and is difficult to extend (depending on the environment).

The singleton model conflicts with the principle of single responsibility. A class should implement only one logic, regardless of whether it is singleton or not.

Realization of singleton pattern

There are many ways to implement the singleton pattern, but various ways of implementation have their advantages and disadvantages. Let's take a look at the various ways of implementation.

The implementation of the singleton pattern satisfies the following points: the constructor is private. There is a static method to get an instance of this class. Only one instance of this class is guaranteed.

Lazy style

Lazybones are created when this object is used.

Lazy, it is only created for you when you need a singleton pattern class instance (because it is lazy).

Pros: this object is created only when it is used, thus saving resources.

The simple implementation is as follows:

/ * Singleton class, singleton schema class, creates a private static variable instance, that is, a real * example of the class when the class is loaded, and then publishes the instance * / public class Singleton {private static Singleton instance; / / privatization constructor to prevent the external new object private Singleton () {via the public interface getInstance ()

}

/ / the public static function exposes the interface of the singleton object

Public static Singleton getInstance () {

If (instance = = null) {

Instance = new Singleton ()

}

Return instance

}

}

However, this approach does not guarantee that this is the only singleton. Under highly concurrent access, when multiple threads access the singleton at the same time, it may not guarantee that the class is singleton.

To ensure thread safety, we can add a lock to the getInstance () method and add a thread synchronization lock synchronize as follows:

Public class Singleton {private static Singleton instance; private Singleton () {} public static synchronized Singleton getInstance () {if (instance = = null) {instance = new Singleton ();} return instance;}}

However, once this method is locked, although it can ensure singleton and thread safety, the performance must be affected under high concurrent access. When multiple threads need to use this singleton, the speed cannot be guaranteed. You need to wait synchronously for this singleton to return to the Heap in JVM before you can continue to use this singleton, which is very inefficient.

There is also a double check, two judgments.

Implementation of singleton pattern by Double Check Lock (DCL)

Public class Singleton {private volatile static Singleton instance; private Singleton () {} public static Singleton getInstance () {if (instance = = null) {synchronized (Singleton.class) {if (instance = = null) {instance = new Singleton ();} return instance;}}

We can see that getInstance has twice judged whether instance is empty. The first judgment is mainly to avoid unnecessary synchronization problems, and the second judgment is to create instances in the case of null, because in some cases, the failure problem, that is, DCL failure problem, can be used to deal with this problem, but similarly, the use of the volatile keyword will also have a certain impact on performance. However, the advantage is that the resource utilization is high, and the object is instantiated only when the getInstance is executed for the first time, but DCL also has some defects in the case of high concurrency because of its slow response to the first load.

Hungry Han style

On the contrary, hungry Chinese and lazy Chinese create an instance when the class is loaded.

The singleton pattern class can't wait to create an instance (because I'm hungry)

Pros: create it before you use it, wasting resources.

Cons: created when the class is loaded, thread-safe.

The implementation is as follows:

/ * this method completes initialization when the class is loaded, so the class loads slowly, but gets the object faster. This method * is based on the class loading mechanism and avoids the problem of multi-thread synchronization. If this instance has never been used, it will result in a waste of memory. * / public class Singleton {private static Singleton instance = new Singleton (); private Singleton () {} public static Singleton getInstance () {return instance;}}

Anonymous inner class / static inner class

Static variables, static code blocks, and static methods are all loaded only once when the class is loaded.

Implement the following

The public class Singleton {private static Singleton instance; / / static block is executed when the class is loaded, thus creating an instance of the Singleton class static {instance = new Singleton ();} private Singleton () {} public static final Singleton getInstance () {return SingletonHolder.INSTANCE The characteristic of the Java static inner class is that the internal static class is not loaded when it is loaded, but only when it is used. * sInstance is not initialized when the Singleton class is loaded for the first time, only when the getInstance method is called for the first time * the virtual machine loads SingletonHolder and initializes sInstance. This ensures not only thread safety, but also the uniqueness of the * Singleton class. Therefore, it is recommended to use static inner class singleton pattern * / public class Singleton {private static class SingletonHolder {private static final Singleton INSTANCE = new Singleton ();} private Singleton () {} public static final Singleton getInstance () {return SingletonHolder.INSTANCE;}} enumerated singleton pattern / * default enumeration instance creation is thread-safe and is singleton in any case. * the point of enumerating a single example is that it is simple, but the disadvantage is that it is not readable. * / public enum Singleton {/ / external calls have changed from Singleton.getInstance to Singleton.INSTANCE. INSTANCE;} Summary

Singleton mode is a mode that is used frequently, and there is usually no high concurrency in our client, so which one we choose will not have much impact. For efficiency reasons, it is recommended to use the singleton mode of static inner classes and the singleton mode of DCL.

Advantages:

Because the singleton mode has only one instance in memory, which reduces memory overhead, especially when an object needs to be created and destroyed frequently, and the performance cannot be optimized when creating or destroying, the advantage of the singleton mode is very obvious.

Because the singleton pattern generates only one instance, the performance overhead of the system is reduced. When the generation of an object requires more resources, such as reading configuration and generating other dependent objects, it can be solved by directly generating a singleton object when the application is started, and then using permanent residence.

Singleton mode can avoid multiple occupation of resources, such as the operation of a file, because only one instance exists in memory, avoiding the simultaneous operation of the same resource file.

Singleton mode can set global access points in the system, optimize and share resource access. For example, you can design a singleton class that is responsible for mapping all data tables.

Disadvantages:

The singleton pattern generally has no interface, and it is difficult to extend unless the code is modified.

If a singleton object holds a Context, it is easy to cause a memory leak, so it is important to note that the Context passed to the singleton object is preferably Application Context.

It is not suitable for objects that change frequently; if the instantiated object is not used for a long time, the system will think that the object is garbage and be recycled, which may lead to the loss of object state.

Working with scen

Website traffic counter.

The class used to read the configuration file in the project.

In Spring, each Bean is singleton by default, which makes it easy for the Spring container to manage.

This is the end of the content about "how to implement the singleton pattern of Java". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report