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

Several common singleton modes in java

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

Share

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

This article mainly shows you "several common singleton patterns in java". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "several common singleton patterns in java".

Singleton pattern: a commonly used software design pattern whose core structure contains a special class called singleton. A class has only one instance, that is, a class has only one object instance.

For some classes in the system, only one instance is important, for example, there can be multiple printing tasks in a system, but only one working task; when selling tickets, there are a total of 100 tickets, but there are multiple windows that sell tickets at the same time, but you need to make sure you don't oversell (the ticket margin here is a singleton, and ticket sales involve multithreading). If you do not unify the window object with a mechanism, multiple windows will pop up, and if these windows display the same content, repeated creation will be a waste of resources.

Application scenario (source: "lie Design pattern"):

Requirements: create a toolbox window at the front end, and either the toolbox does not appear or only one

Problem: the Toolbox window will be created repeatedly every time you click on the menu.

Solution 1: use the if statement to determine whether it is null each time you create an object, and then create an object for null.

Requirements: if you need to instantiate the toolbox form in 5 places

Encountered a problem: this small bug needs to change 5 places, and the code is duplicated and the code utilization is low.

Solution 2: use the singleton pattern to ensure that there is only one instance of a class and provide a global access point to it.

In the following ways, we will find that all singleton patterns are created using static methods, so singleton objects are stored in static shared areas in memory. (please refer to https://zhidao.baidu.com/question/2206072272164938188.html)

The singleton model can be divided into lazy type and hungry type:

Lazy singleton mode: does not initialize when the class is loaded.

Hungry Han singleton mode: initialization is completed when the class is loaded, so the class loading is slow, but the speed of getting objects is fast.

The first (slacker, thread unsafe):

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

This way of writing lazy loading is obvious, but the fatal thing is that it doesn't work properly in multithreading.

The second (lazy, thread safe):

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

This writing adds a synchronized lock to the getInstance () method. It works well in multithreading, and it seems to have a good lazy loading, but it is inefficient (because of locks) and in most cases does not require synchronization.

The third kind (hungry):

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

This approach avoids the problem of multithreading synchronization based on the classloder mechanism, but instance is instantiated when the class is loaded, and initializing instance obviously does not achieve the effect of lazy loading.

The fourth (hungry man, variety):

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

On the surface, it seems to be quite different, but in fact, the third way is similar, which is to instantiate instance in class initialization.

The fifth (static inner class):

Public class SingletonDemo5 {private static class SingletonHolder {private static final SingletonDemo5 instance = new SingletonDemo5 ();} private SingletonDemo5 () {} public static final SingletonDemo5 getInsatance () {return SingletonHolder.instance;}}

This approach also uses classloder's mechanism to ensure that there is only one thread when initializing instance, which is (slightly different) from the third and fourth methods: as long as the Singleton class is loaded, then the instance is instantiated (not lazy loading), while in this way the Singleton class is loaded and the instance is not necessarily initialized. Because the SingletonHolder class is not actively used, the load SingletonHolder class is displayed only when the getInstance method is called, thus instantiating the instance. Imagine that if instantiating instance is resource-consuming and I want him to delay loading, on the other hand, I don't want to instantiate when the Singleton class loads, because I can't guarantee that the Singleton class may be actively used and loaded elsewhere, then instantiating instance at this time is obviously not appropriate. At this time, this approach is more reasonable than the third and fourth methods.

Type 6 (enumeration):

Public enum SingletonDemo6 {instance; public void whateverMethod () {}}

This approach is advocated by Josh Bloch, the author of Effective Java, which can not only avoid the problem of multithreaded synchronization, but also prevent deserialization from recreating new objects, which is a very strong barrier. However, I personally think that as a result of the addition of enum features in 1.5, writing in this way inevitably makes people feel rusty, and in actual work, I rarely see people write like this.

Seventh (double check lock):

Public class SingletonDemo7 {private volatile static SingletonDemo7 singletonDemo7; private SingletonDemo7 () {} public static SingletonDemo7 getSingletonDemo7 () {if (singletonDemo7 = = null) {synchronized (SingletonDemo7.class) {if (singletonDemo7 = = null) {singletonDemo7 = new SingletonDemo7 ();} return singletonDemo7;}}

This is an upgraded version of the second method, commonly known as double-checked locking. For more information, please see: http://www.ibm.com/developerworks/cn/java/j-dcl.html

After JDK1.5, double-check locking can achieve the singleton effect normally.

A single instance in a multithreaded program, where multiple threads access the singleton at the same time, it is possible to create multiple instances. At this point, it needs to be locked up with a "lock". Including lock, deadlock, communication between locks, this part about multithreading needs to be explained in detail later!

These are all the contents of this article entitled "several singleton modes common in java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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