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 pattern in the web design pattern

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article introduces the knowledge of "what is the singleton pattern in web design pattern". 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!

Singleton pattern (Singleton Pattern) is widely used, for example, our controller and service are both singleton, but it is different from the standard singleton pattern. This type of design pattern is a creative pattern, which provides the best way to create objects. This pattern 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 unique object directly without instantiating the object of the class.

Pattern structure

The structure of the singleton pattern is very simple, involving only one singleton class, the construction method of this singleton class is private, and the class itself defines a static private instance. and provide a static public function to create or get the static private instance.

Source code guide

The singleton mode is divided into lazy singleton and hungry singleton. The code for hungry singleton is very simple. As the name implies, hungry singleton is created when the class is initialized. The sample code is as follows:

Public class Singleton {private static final Singleton singleton = new Singleton (); / / restrict the generation of multiple objects private Singleton () {} / / obtain other methods in the instance object public static Singleton getSingleton () {return singleton;} / / class by this method, as far as possible static public static void doSomething () {}}

But the lazy singleton is not so simple. When accessing the instance of this class, the lazy singleton first determines whether the instance of this class has been created, and if it is not created, create the singleton first. In other words, the lazy singleton creates the singleton on the first visit, not the initialization phase. This will lead to a problem. If, in a multithreaded scenario, multiple threads access the singleton at the same time and find that it has not been created, then these threads will create instances separately. Then the singleton pattern is not so singleton-- the instance is created multiple times. In the Ali development manual, there are two items related to lazy singles, telling us how to avoid this situation, articles 1 and 12 of section 6:

(6) concurrent processing

1. [force] to obtain singleton objects, you need to ensure thread safety, and the methods also need to ensure thread safety.

Description: resource-driven classes, tool classes, singleton factory classes all need to be paid attention to.

[recommended] in concurrent scenarios, double check locks (double-checked locking) are used to achieve delayed initialization.

Change the hidden trouble of the problem, recommend the solution.

One of the simpler solutions (for JDK5 and above) declares the target attribute as volatile.

Counterexample:

Class Singleton {private Helper helper = null; public Helper getHelper () {if (helper = = null) synchronized (this) {if (helper = = null) helper = new Helper ();} return helper;} / / other methods and fields... }

The role of the volatile keyword and double check lock have been introduced in my previous blog, the article address https://mp.weixin.qq.com/s/r52hmD71TtiJjlOzQUvRlA this blog introduces some knowledge of concurrency, friends can read it when they are free. Here, the function of the volatile keyword is to ensure the visibility of the data, and the double-check lock is to improve the performance of the code. Let's analyze the counterexamples in the manual:

Its double detection lock refers to this code:

If (helper = = null) synchronized (this) {if (helper = = null) helper = new Helper ();}

If you don't double check locks here, you can only lock on the entire getHelper method, because this method must ensure that only one thread executes helper = new Helper (); in concurrency. In other words, the code looks like this:

Public synchronized Helper getHelper () {if (helper = = null) {if (helper = = null) helper = new Helper ();} return helper;}

The locking performance of the whole method is obviously not good, and the granularity of the lock becomes larger; why do you make two if judgments in the double check lock? this question is left to the reader to think about, and it is not a particularly difficult question. But visibility is not taken into account in the counterexample-suppose thread an and thread b access the getHelper method at the same time, then thread b is blocked, thread a finds that helper is not instantiated, executes the new method, and then releases the lock When the b thread comes in, maybe our intuitive feeling is that the b thread finds that the property is instantiated and returns helper directly, but in fact it is not. When a thread modifies the common resource shared by the thread (in this case, the helper property) other threads may not be notified that the property has been modified, so the b thread may find that helper or null may also know that the helper has been assigned. This can be avoided by using volatile. So the correct code should look like this:

Class Singleton {private volatile Helper helper = null; public Helper getHelper () {} / / other methods and fields... } this is the end of the content of "what is the singleton pattern in the web design 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.

Share To

Internet Technology

Wechat

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

12
Report