Design Pattern 1---single case mode

Source: Internet
Author: User

Single case Mode singletonWord 827 Read 224 Comments 0 likes

This is my study of "Android source design mode analysis and combat" in the process of a single-case mode to make a record. Convenient to look at anytime later.
Singleton mode is one of the most widely used patterns, using the following 常见场景 : Network requests, access to the IO, database and thread pool are very resource-intensive cases, you can consider using singleton mode.

The central principle is:

    • Ensure that the Singleton class has only one object, especially in a multithreaded environment.
    • Ensure that the object is not rebuilt when deserializing.
A Hungry man mode

A singleton instance is built when the class is loaded. Privatize the constructor so that external programs must not create objects through constructors, only static methods can return a unique static object.

  public class Singleton{      private static final Singleton sInstance = new Singleton(); //构造函数私有化 private Singleton(){} public static Singletoon getInstance() { return sInstance; } }
Lazy mode

The singleton instance is initialized the first time it is called.

The lazy pattern is implemented as follows:

public class singleton {private static Singleton instance; private Singleton () {} public  Static synchronized Singleton getinstance  () {if (instance = = null) {instance = new Singleton ();} return instance;}           

Synchronized is added to the static method that obtains the singleton object, which guarantees the uniqueness of the Singleton object under multithreading.

缺点:

    • The first load needs to be instantiated and the reaction is slightly slower.
    • Each call to getinstance () is synchronized, causing a lot of unnecessary synchronization overhead.
      Therefore, the general 不建议使用 lazy mode.
Volatile double-check lock (double-checked locking)
PublicClassSingleton {private static Singleton instance = NULL;Prevents the DCL from failing, ensuring that the instance object is read from the live memory every time.Privatestatic volatile Singleton instance = null; private Singleton () {} public  Static Singleton getinstance () {// Avoid unnecessary synchronization if (instance = null) {//Create an instance under instance = null if ( Instance = = null) {instance = new Singleton ();}}} return instance;}           

缺点:

    • JDK1.5 the above version is volatile.

优点:

    • Resource utilization is high, the first execution of getinstance () will be instantiated, high efficiency.

It just looks perfect.

This seemingly perfect optimization technique is double-checked locking, but I regret to tell you, according to the JLS specification, the above code is unreliable! It is possible for a thread to get an object that is not NULL, but not completely constructed. Why? The unreliable reason is that the compiler is re-queued in order to improve execution efficiency. As long as the single thread is not a problem, it can be written in a disorderly order! To ensure that the CPU instruction pipeline is not interrupted.


Command rearrangement

To improve the efficiency of code execution, the JVM compiles code that executes at a high frequency, and the code with low frequency is still interpreted. Common ways to compile optimizations are: Method inline: Eliminate parameters, return value transfer process to Virtualize: interface method has only one implementation class, the method of inline redundancy elimination: run-time removal of useless code and some compilation optimization based on "escape analysis" technology scalar replacement: User u=new User ("Zhang3 "," String n= "zhang3" int age=18, save on memory stack allocation: The Escape object is allocated directly on the stack, fast, the GC is synchronized in time: Remove unnecessary synchronization


What happened to New Instance ()?

Memory = allocate (); 1: Allocating the object's memory space ctorinstance; 2: Initialize object instance = memory; 3: Set instance point to the memory address just allocated above the pseudo code in 2, 3 steps may reflow






Solutions 1

Java5 later versions, you can take advantage of the volatile keyword. Why? Before Java5, the volatile primitive was not strong, only guaranteed the visibility of the object, but after Java5, the volatile semantics strengthened, the volatile object, which would prohibit read and write instructions on the object, would be guaranteed to be read by the thread B. It's completely initialized.


Solutions 2

This is also the official recommendation of a proposal (effective Java 2nd)

Click ( here) to collapse or open

    1. public class instanceholder{
    2. Private Instance () {}
    3. Lazy initialization Holder Class idiom for static fields
    4. private Static Class inner{
    5. Private static final Instance ins = new Instance ()
    6. }
    7. public static Instance getinstance () {
    8. return inner.ins;
    9. }

Principle: A class is initialized only when it is used, and the class initialization process is non-parallel, which is guaranteed by JLS. Static internal class Singleton mode

In the Java concurrency programming practice, which mentions the problem of the DCL failure (the part commented in the volatile double-check lock example above), it is recommended to replace it with the following code:

Publicclass singleton {private static final Singleton sInstance; private singleton  () {} public  Static Singleton getinstance () { return singletonholder.sinstance; } private static class singletonholder {sinstance = new Singleton ( ); }} 

优点:

    • Resource utilization is high, the first execution of getinstance () will be instantiated, high efficiency.
    • Not only to ensure the thread safety, but also to ensure the uniqueness of the Singleton object, but also delay the instantiation of the Singleton, so this is 推荐使用 the singleton mode implementation mode.
Enumeration single Example
public class SingletonEnum {    INSTANCE;    public void doSomething() { //do something; }}

优点:

    • Enumerations in Java, like normal classes, can have fields, methods. The instance created by the default enumeration is thread-safe.
    • Single-instance self-serialization with enum implementation.

However, several of the above-mentioned singleton pattern implementations will recreate the object when deserializing. To prevent a singleton object from being rebuilt, you must include the following methods:

private Object readResolve() throws ObjectStreamException { return sInstance;}
Resources
    • [1] "Android source design mode analysis and actual combat"
    • [2] Java concurrency programming practice

Design Pattern 1---single case mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.