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

The singleton pattern of messing with Java design pattern

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

The original site of the blog post: the singleton pattern of trespassing the Java design pattern

Singleton mode

Ensure a class has only one instance, and provide a global point of access to it.

A class has only one instance and provides a global access point. A concise understanding involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its own unique object, which can be accessed directly without instantiating the object of the class.

Public final class EagerSingleton {private static final EagerSingleton INSTANCE = new EagerSingleton (); private EagerSingleton () {} public static EagerSingleton getInstance () {return INSTANCE;}}

The synchronization problem of multithreading is avoided 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. The class is initialized when it is loaded, which wastes space because it is created whether you use it or not, but it is more efficient because it is not locked.

Lazy singleton mode / * * lazy singleton mode-thread unsafe * / public final class LazyThreadNotSafeSingleton {private static LazyThreadNotSafeSingleton INSTANCE; private LazyThreadNotSafeSingleton () {} public static LazyThreadNotSafeSingleton getInstance () {if (null = = INSTANCE) {INSTANCE = new LazyThreadNotSafeSingleton ();} return INSTANCE }} / * lazy singleton mode-thread safe * / public final class LazyThreadSafeSingleton {private static LazyThreadSafeSingleton INSTANCE; private LazyThreadSafeSingleton () {} public static synchronized LazyThreadSafeSingleton getInstance () {if (null = = INSTANCE) {INSTANCE = new LazyThreadSafeSingleton ();} return INSTANCE;}}

There are the above two lazy singleton modes, which are different from the static factory method getInstance with synchronized modification for synchronization to support thread safety. Lazy type, it will not create an object instance when it loads the object, but will only create it when it is actually used, and will not be created if it has not been used all the time, which can avoid memory waste, that is, it will be created only when it is called for the first time. However, locking synchronized affects performance and efficiency, resulting in an impact on the performance of the getInstance method, which is not recommended. Look for a way that can both thread-safe and delay loading.

Singleton mode of double check lock / * * singleton mode of double check lock-thread safety * / public final class DoubleCheckLockingSingleton {private static volatile DoubleCheckLockingSingleton INSTANCE Private DoubleCheckLockingSingleton () {} public static DoubleCheckLockingSingleton getInstance () {/ / check whether the instance exists for the first time, and return it if it does not exist. If not, enter the synchronization block if (null = = INSTANCE) {/ / synchronization block, and thread-safe synchronized (DoubleCheckLockingSingleton.class) {/ / check the instance existence for the second time. If it does not already exist, the instance if (null = = INSTANCE) {INSTANCE = new DoubleCheckLockingSingleton () will actually be created. } return INSTANCE;}}

Double check locking can not only achieve thread safety, but also reduce the impact of performance. Double check locking is designed to synchronize each call to the getInstance method, but it will not be synchronized first. After determining whether the instance exists for the first time, enter the synchronization block if it does not exist. After entering the synchronization block, check whether the instance exists for the second time. If it does not exist, create an instance in the synchronization block. In this way, it will only be synchronized for the first time, thus reducing the time wasted by making multiple judgments in the case of synchronization. The implementation of the double-check locking mechanism uses the keyword volatile, which means that the value of the variable modified by volatile will not be cached by the local thread, and all reads and writes to the variable will directly operate on the shared memory, thus ensuring that multiple threads can handle the variable correctly. But the implementation process is a little more complicated.

Static internal class Holder singleton mode / * * static internal class Holder singleton * * delayed loading and thread safety * / public final class LazyInitializationHolderSingleton {private LazyInitializationHolderSingleton () {} public static LazyInitializationHolderSingleton getInstance () {return InstanceHolder.INSTANCE;} / * delayed loading * / private static class InstanceHolder {private static final LazyInitializationHolderSingleton INSTANCE = new LazyInitializationHolderSingleton ();}}

When the getInstance method is called for the first time, it reads InstanceHolder.INSTANCE for the first time, causing the InstanceHolder class to be initialized; and when this class is loaded and initialized, it initializes its static domain, thus creating an instance of Singleton. Because it is a static domain, it is initialized only once when the virtual machine loads the class, and the virtual machine ensures its thread safety. The advantage of this pattern is that the getInstance method is not synchronized and only performs access to a domain, so delayed initialization does not add any access costs. The static inner class of the class and multithreaded default synchronization locks are used.

Static inner class

A static inner class is a member inner class with static modification. A member inner class without static modification is called an object-level inner class. A class-level inner class is equivalent to the static component of its external class, and there is no dependency between its object and the external class object, so it can be created directly. The instance of the object-level inner class is bound in the external object instance. In static inner classes, static methods can be defined. Only static member methods or member variables in an external class can be referenced in static methods. A static inner class is equivalent to a member of its external class and is loaded only the first time it is used.

Multithreaded default synchronization lock

In multithreaded development, in order to solve the concurrency problem, synchronization control is mainly carried out by using synchronized to add mutex lock. But in some cases, JVM has implicitly performed synchronization for you, in which case you no longer have to do synchronization control yourself. These situations include:

1. When data is initialized by a static initializer (on a static field or in a static {} block)

two。 When accessing the final field

3. When you create an object before creating a thread

4. When a thread can see the object it is about to process

The singleton pattern of enumerated types / * adopts the singleton pattern of enumerated types * / public enum SingletonEnum {INSTANCE; @ Override public String toString () {return getDeclaringClass (). GetCanonicalName () + "@" + hashCode ();} public void something () {/ / do something... }}

Concise, automatic support for serialization mechanism, absolutely prevent multiple instantiations. As stated in the second edition of efficient Java: enumerated types of single elements have become the best way to implement Singleton. Implementing a singleton with enumerations is as simple as writing an enumerated type that contains a single element.

Summary

It is not recommended to use lazy style, simple wide to use hungry Chinese style. When it comes to deserialization, create objects wide to use enumerations. If delayed loading is taken into account, the mode of static inner class Holder is adopted. If there are special requirements for business requirements, a single case of double check locks should be used.

Referenc

Source code address

Singleton mode | Rookie tutorial

The singleton Model of "JAVA and Mode"

Welcome to stay tuned for the latest dynamic updates.

Cdn.xitu.io/2019/1/25/168827caf090df03?w=258&h=258&f=jpeg&s=19969 ">

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

Internet Technology

Wechat

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

12
Report