Detailed explanation of single example mode of Android programming design mode

This paper describes the single example mode of Android programming design mode. Share with you for your reference, as follows:

1、 Introduction

Singleton pattern is one of the most widely used patterns, and it may also be the only design pattern that many junior engineers will use. When applying this pattern, the class of a singleton object must ensure that only one instance exists. Many times, the whole system only needs to have a global object, which is conducive to coordinating the overall behavior of the system.

2、 Definition

Ensure that a class has only one instance, instantiates itself and provides this instance to the whole system.

3、 Usage scenario

Ensure that there is only one object in a class to avoid excessive resource consumption of multiple objects, or there should be only one object of a certain type. For example, creating an object consumes too many resources, such as accessing IO, database and other resources. In this case, the singleton mode should be considered.

4、 Implementation mode

1. Hungry man model

Example code:

Advantages: delayed loading (loading only when needed)

Disadvantages: the thread is unsafe. It is easy to be out of sync in multithreading, such as frequent read and write operations on database objects.

2. Lazy mode

Example code:

Compared with the hungry man mode, the synchronized keyword is added to the getInstance () method, that is, getInstance is a synchronous method, which is a means to ensure the uniqueness of singleton objects in the case of multithreading. However, if you think about it carefully, you may find a problem. Even if instance has been initialized (instance will be initialized when it is called for the first time), the getInstance method will be synchronized every time it is called, which will consume unnecessary resources, which is also the biggest problem of the lazy model.

Advantages: it solves the problem of thread insecurity.

Disadvantages: it needs to be instantiated in time during the first load, and the response is slightly slow. The biggest problem is that getInstance is synchronized every time it is called, resulting in unnecessary synchronization overhead.

Supplement: the singleton methods used in the Android source code are: inputmethodmanager, accessibilitymanager, etc. all use this singleton mode

3. Double check lock (DCL)

Example code:

The highlight of this program is naturally in the getInstance method. You can see that the instance is judged null twice in the getInstance method: the first layer judgment is mainly to avoid unnecessary synchronization, and the second layer judgment is to create an instance in the case of null.

Suppose thread a executes the instance = new singleton() statement. It looks like a code here, but in fact it is not an atomic operation. This code will eventually be compiled into multiple assembly instructions. It does roughly three things:

(1) Allocate memory for instances of singleton;

(2) Call the constructor of singleton() to initialize the member field;

(3) Point the instance object to the allocated memory space (instance is not null at this time).

However, because the java compiler allows the processor to execute out of order, and the provisions on the write back order from cache and register to main memory in JMM (JAVA memory model) before JDK1.5, the order of the second and third sentences above cannot be guaranteed. That is, the execution order may be 1-2-3 or 1-3-2. If it is the latter, and it is switched to thread B before 3 is executed and 2 is not executed, at this time, because the instance has executed the third point in thread a, the instance is not empty. All thread B takes the instance directly, and an error will occur when it is reused. This is the problem of DCL failure, Moreover, such errors that are difficult to track and reproduce are likely to be hidden for a long time.

After JDK1.5, sun officials have noticed this problem, adjusted the JVM and specified the volatile keyword. Therefore, if the JDK is version 1.5 or later, you only need to change the definition of instance to private volatile static singleton instance to ensure that the instance object is read from main memory every time, and you can use the writing method of DCL to complete the singleton mode. Of course, volatile will also affect performance more or less, but considering the correctness of the program, it is worth sacrificing this performance.

Advantages: high resource utilization. The singleton object will be instantiated only when getInstance is executed for the first time, which is efficient. In the case of low concurrency and low security, the singleton mode may run perfectly

Disadvantages: the response is slightly slow when loading for the first time, and occasionally fails due to the JAVA memory model. There are also some defects in the high concurrency environment, although the probability of occurrence is very small.

Add: in the Android image open source project Android universal image loader( https://github.com/nostra13/Android-Universal-Image-Loader )This method is used in. DCL mode is the most used singleton implementation method. It can instantiate singleton objects when needed, and ensure the uniqueness of singleton objects in most scenarios. Unless your code is used in complex concurrent scenarios or lower than JDK6 version, this method can generally meet the needs.

4. Static inner class singleton mode

Although DCL solves the problems of resource consumption, redundant synchronization and thread safety to a certain extent, it still fails in some cases. This problem is called double check locking (DCL) failure. This problem is discussed at the end of the Book Java Concurrent Programming practice, and it is pointed out that this "optimization" is ugly and does not approve of its use. Instead, it is recommended to use the following code instead:

Example code:

Instance will not be initialized when the singleton class is loaded for the first time. Instance will be initialized only when the getInstance method of singleton is called for the first time. Therefore, calling the getInstance method for the first time will cause the virtual machine to load the singletonholder class. This method can not only ensure thread safety, but also ensure the uniqueness of the singleton object. At the same time, it also delays the instantiation of the singleton. Therefore, this is the recommended singleton mode implementation method.

Advantages: delayed loading, thread safety (mutually exclusive when loading classes in Java), and reduced memory consumption

5. Enumeration singleton

Previously, we explained some implementation methods of singleton mode, but these implementation methods are either a little troublesome or there will be problems in some cases.

Example code:

Simple writing is the biggest advantage of enumerating singletons. Enumerations are the same as ordinary classes in Java. They can not only have fields, but also have their own methods. Most importantly, the creation of the default enumeration instance is thread safe, and in any case it is a singleton.

Why do you say that? In the above singleton pattern implementations, in one case, they will recreate the object, that is, deserialization.

Through serialization, an instance object of a singleton can be written to disk and then read back, so as to effectively obtain an instance. Even if the constructor is private, you can still create a new instance of the class in a special way during deserialization, which is equivalent to calling the constructor of the class. The deserialization operation provides a special hook function. The class has a private and instantiated method readresolve (), which allows developers to control the deserialization of objects. For example, in the above examples, if you want to prevent the singleton object from regenerating the object when it is deserialized, you must add the following methods:

That is, return the instance object in the readresolve method instead of regenerating a new object by default. For enumeration, this problem does not exist because even if it is deserialized, it will not regenerate a new instance.

Advantages: the serialization mechanism is provided free of charge to absolutely prevent multiple instantiations, even in the face of complex serialization or reflection attacks.

Disadvantages: supported from Java 1.5.

The above mainly describes the five creation methods of singleton mode, which can be used in personal actual projects according to their advantages and disadvantages.

More readers interested in Android related content can view the special topics of this site: introduction and advanced tutorial of Android development, summary of Android debugging skills and common problem solving methods, summary of Android basic component usage, summary of Android view skills, summary of Android layout skills and summary of Android control usage

I hope this article will help you in Android programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>