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

What is the singleton mode of Java?

2025-02-24 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 "what is the singleton model of Java". In the operation of actual cases, many people will encounter such a dilemma, 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!

Double check mode

Public class Singleton {private volatile static Singleton singleton; / / 1:volatile modifies private Singleton () {} public static Singleton getSingleton () {if (singleton = = null) {/ / 2: reduce non-synchronization, optimize performance synchronized (Singleton.class) {/ / 3: synchronization, thread-safe if (singleton = = null) {singleton = new Singleton (); / / 4: create singleton objects} return singleton;}

Reasons for recommendation:

Delayed initialization. Consistent with the lazy pattern, the signleton instance is initialized only when the static method getSingleton is called for the first time. Performance optimization. Synchronization will cause performance degradation, and the unnecessary synchronization overhead can be reduced by judging whether the singleton is initialized before synchronization. Thread safety. Create the Singleton object synchronously, and notice that the static variable singleton is decorated with volatile.

Why use volatile retouching?

Although synchronized has been used for synchronization, when you create the object in step 4, you will have the following pseudo code:

Memory=allocate (); / / 1: allocate memory space ctorInstance (); / / 2: initialize object singleton=memory; / / 3: set singleton to point to the memory space just sorted

When thread An is executing the pseudocode above, reordering may occur in 2 and 3, because reordering does not affect the running results and can improve performance, so JVM is allowed. If the pseudo code is reordered at this time, and the step changes to 1-> 3-> 2, thread B calls the getsingleton method when thread An executes step 3, and it is not null when judging singleton==null, then singleton is returned. But at this point, the singleton has not been initialized, and thread B will access an object that has not been initialized. When the reference to the object is declared as volatile, the reordering of 2 and 3 of the pseudo code will be prohibited in multithreading!

Static inner class mode

Public class Singleton {private Singleton () {} public static Singleton getSingleton () {return Inner.instance;} private static class Inner {private static final Singleton instance = new Singleton ();}}

Reasons for recommendation:

The implementation code is simple. Compared with the double check singleton, the static internal class singleton implementation code is really too concise and clear. Delayed initialization. The Singleton object is initialized by calling getSingleton. Thread safety. During the initialization phase of the execution class, JVM acquires a lock that can synchronize initialization of the same class by multiple threads.

How to achieve thread safety?

Thread An and thread B both try to acquire the initialization lock of the Singleton object, assuming thread An acquires it, then thread B waits for the initialization lock. Thread A performs class initialization, and even if the pseudo code is reordered in double-check mode, the initialization result of thread A will not be affected. After initialization, release the lock. Thread B acquires the initialization lock, finds that the Singleton object has been initialized, releases the lock, and acquires the Singleton object without initialization.

In singletons involving reflection and serialization, it is recommended to use the enumerated type pattern below.

Other types of singleton patterns

Lazy mode (multithreading is not safe)

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

Hungry singleton model (multi-thread security)

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

The thread safety of hungry mode also solves the synchronization problem through class loading, but does not achieve the purpose of lazy loading. (thank you very much for the correction of z-chu at the beginning.)

Enumerate singleton patterns (multi-threaded security)

Public enum Singleton {INSTANCE; public void doSomething () {/ / todo doSomething}}

This method is recommended in Joshua Bloch's "Effective Java". Although thread-safe, it has not been widely adopted in actual development. Because it is so concise that it has poor readability, it has not been widely promoted in actual combat. The thread safety of enumerating singleton patterns also takes advantage of class initialization locks in static inner classes. Enumerating singleton patterns can guarantee the uniqueness of instances in serialization and reflection.

If there are fights between experts, you must choose enumerated singleton mode.

This is the end of the content of "what is the singleton mode of Java"? thank you for your 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.

Share To

Development

Wechat

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

12
Report