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 are the two java singleton modes?

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

Share

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

This article mainly explains "which two kinds of java singleton mode are divided into". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn which two kinds of java singleton mode.

Definition:

Singleton pattern is a commonly used software design pattern. Its core structure contains only one special class called a singleton. The singleton mode can ensure that there is only one instance of a class in the system. That is, there is only one object instance for a class.

Features:

1. A singleton class can only have one instance.

2. The singleton class must create its own unique instance.

3. The singleton class must provide this instance to all other objects

The main points of the singleton model:

1. Private construction method

2. Private static reference to your own instance

3. A static public method with its own instance as the return value

The singleton pattern is divided into two types depending on the timing of the instantiated object:

One is the hungry Han style, and the other is the lazy Han style.

The hungry Chinese singleton instantiates an object to its own reference when the singleton class is loaded, while the lazy Chinese instantiates the object only when the instance method is called.

The code is as follows:

A single case of hungry Han style

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

Single case of lazy Chinese style

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

There is also a common form of singleton pattern: the form of double lock.

Public class Singleton {

Private static volatile Singleton instance=null

Private Singleton () {

/ / do something}

Public static Singleton getInstance () {

If (instance==null) {

Synchronized (SingletonClass.class) {

If (instance==null) {instance=new Singleton ();}

Return instance;}} this mode puts the synchronization content down to the inside of the if, which improves the efficiency of execution. It does not have to be synchronized every time an object is obtained, it is only synchronized for the first time, and it is not necessary after it is created. The efficiency of double judgment plus synchronization in this mode is much higher than that in the first example, because if single-tier if judgment is allowed, assuming that there are 100 threads in the server, the time consumed is 100 * (synchronization judgment time + if judgment time), while if double if judgment, 100 threads can be judged by if at the same time, the time consumed in theory is only one if judgment time.

So if you are faced with high concurrency and use lazy mode, the best choice is double judgment plus synchronization.

Advantages of the singleton model:

1, there is only one object in memory, saving memory space.

2. Avoid frequent creation and destruction of objects, which can improve performance.

3. Avoid multiple occupations of shared resources.

4, can be accessed globally.

Advantages of the singleton model:

1. It is difficult to extend because the getInstance static function has no way to generate instances of subclasses. If you want to expand, you have to rewrite that class.

2. The implicit use causes the class structure to be unclear.

3, the problem that causes the program memory leak.

Applicable scenarios:

Because of the above advantages of singleton pattern, it is a kind of design pattern which is widely used in programming. The following is a scenario that uses singleton mode:

1, objects that need to be frequently instantiated and then destroyed.

2. Objects that take too much time to create or consume too much resources, but are often used.

3. In the case of resource sharing, avoid the performance or loss caused by resource operation.

4. In the case of controlling resources, it is convenient for resources to communicate with each other.

Singleton mode considerations:

You can only get a singleton object using the methods provided by the singleton class, and do not use reflection, or a new object will be instantiated.

Do not do dangerous operations to disconnect singleton class objects from static references in the class.

When multithreading uses singletons to use shared resources, pay attention to thread safety issues.

Some common questions about the singleton pattern in Java:

Will singleton objects not be collected by jvm garbage collector for a long time?

The jvm garbage collector will not recycle a singleton object unless it artificially disconnects the join of the static reference to the singleton object in the singleton.

The criteria for jvm uninstall classes are as follows:

1. All instances of this class have been recycled, that is, no instances of this class exist in the java heap.

2. The ClassLoader that loaded the class has been recycled.

3, the corresponding java.lang.Class object of this class is not referenced anywhere, and the methods of this class cannot be accessed anywhere through reflection.

Jvm will unload classes during garbage collection only if all three conditions are met. Obviously, the singleton class does not meet condition one, so the singleton class will not be recycled.

Will there be multiple singles in a jvm?

In the case of distributed systems, multiple classloaders, and serialization, there is no doubt that multiple singletons will be generated. So is there a singleton in the same jvm? You can only get the same singleton using the getInstance () method provided by the singleton, and unless you are using reflection, you will get a new singleton.

The code is as follows:

Class c = Class.forName (Singleton.class.getName ()); Constructor ct = c.getDeclaredConstructor (); ct.setAccessible (true); Singleton singleton = (Singleton) ct.newInstance ()

In this way, each run produces a new singleton object. So when using singleton mode, be careful not to use reflection to generate new singleton objects.

Does synchronization have an advantage over the getInstance () method, or is it better to synchronize only the necessary blocks?

Because locking makes sense only when you create an instance, and then at other times the instance is only read-only, it is better to synchronize only the necessary blocks and is a better choice.

Cons: only on the first call will 2 objects be generated and synchronization must be required. Once the singleton is not null, the system still costs synchronization lock overhead, and the loss outweighs the gain.

Can singleton classes be inherited?

The singleton pattern can be divided into several types according to the timing and mode of constructing the singleton instance. However, inheritance is not supported for this singleton class where instances are provided by static methods through privatized constructors.

The singleton implementation of this pattern requires each specific singleton class itself to maintain singleton instances and limit the generation of multiple instances. However, we can use another way to implement the singleton: registered singleton, to make the singleton open to inheritance.

Thank you for your reading, the above is the content of "which two java singleton modes are divided into". After the study of this article, I believe you have a deeper understanding of which two java singleton modes are divided into, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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