Analysis of Eight Posture Writing Methods for Single Case Mode

Catalog

Preface
There are 7 and 6 types of writing in the pattern of online flooding leaflets. Of course, there are 5. Are they wrong?Actually, there is no right or wrong. Ask after all, writing is ultimately writing, and its essence is basically the same!So there is no need to find out how much writing is. It's better to follow Yichun to the Internet cafe to steal headphones and go to the field to catch frogs. Every day...

Back to the truth.. Singleton mode is one of the most commonly used design modes. Friends who are familiar with design mode will never be unfamiliar with singleton mode.The singleton pattern is also a design pattern that is easy to understand.

@

What is the singleton mode?

Technical Term

The singleton pattern is a common software design pattern that defines that a class of singleton objects can only allow one instance to exist.Many times the whole system only needs to have one global object, which is good for us to coordinate the overall behavior of the system.For example, in a server program, the configuration information of the server is stored in a file, which is read uniformly by a single object, and then obtained by other objects in the service process.This simplifies configuration management in complex environments.

The singleton pattern simply means that a class can only have one instance, and that instance is accessible throughout the project.

Advantages of the singleton pattern

1. There is only one object in memory to save memory space.
2. Avoiding frequent creation and destruction of objects can improve performance.
3. Avoid multiple occupation of shared resources.
4. It can be accessed globally.

Single Case Mode Implements the Whole Idea Process

First, we need to be clear that the singleton pattern requires that the class have a reference to the returned object (always the same) and a method to get the instance (must be static, usually by the name getInstance).

The general implementation ideas of the singleton pattern are roughly the same as the following three steps:

1. Private construction methods
2. Private static references to their own instances
3. Statically public methods that return values from their own instances

Of course, it can also be understood as
1. Privatize the construction method so that the outside cannot be new.
2. Create object instances within this class [Static variables are designed to create instances when the class loads]
3. Provide a public static method (which typically uses the name getInstance) that returns an instance object.

Define the class's construction method as a private method so that code elsewhere cannot instantiate the class's objects by calling its construction method, only by the static method provided by the class to obtain a unique instance of the class;
Provides a static method within the class that is returned if the class holds a reference that is not empty when we call this method, and creates an instance of the class if the class holds a reference that is empty and assigns the reference of the instance to the class holds a reference.

Scenarios for Single Case Mode

Since the singleton mode has many unique advantages, it is a design mode used more in programming.I summarize what I know about scenarios that work well with the singleton pattern:

1. Objects that need to be instantiated frequently and then destroyed.
2. Objects that take too much time or resources to create but are often used.
3. Stateful tool class objects.
4. Objects that frequently access databases or files.

Later I'll talk about the Runtime class in JDK as a hungry Chinese singleton!controller in the Spring MVC framework defaults to singleton mode!

Eight Posture Writings for Single Case Mode

Yichun strongly recommends: If you are not in touch with the singleton mode of reader friends strongly suggest that you tap once, do not copy, otherwise it will not work!

Another point is that JVM's knowledge of class loading is essential to truly easily understand the singleton pattern, otherwise you are just hitting the level, what?Don't know class loading?Rest assured that Yichun wants you to understand it thoroughly.

Again, this article gives you an absolute understanding of java class loading and ClassLoader source analysis [JVM 2]

In fact, this article above is especially important. The importance of this article above is to understand the natural understanding. I don't understand it. I want to understand Yichun's good intentions. Check it out. I really can't read it and look back at this article. It's better to press the blogger on the toilet lid together....

Is it warm in my heart?Yichun doesn't beep much anymore, just walk up at the code.

Posture 1: Hungry Han Style 1 (Static Variable)

package singletonPattern;
//Hungry Han Style (Static Variable)

class Singleton{
    //1. Privatization construction method so that external cannot be new
    private Singleton(){

    }
    //2. Create object instances within this class [Static variables are designed to create instances when the class loads]
    private final static Singleton instance=new Singleton();

    //3. Provide a public static method to return instance objects
    public static Singleton getInstance(){
        return instance;
    }
}
//The following is the test code===========================

public class SingletenDemo1 {
    public static void main(String[] args) {
        Singleton singleton=Singleton.getInstance();
        Singleton singleton2=Singleton.getInstance();
//Verify 1:
        System.out.println(singleton==singleton2);
//Verification 2:
        System.out.println(singleton.hashCode());
        System.out.println(singleton2.hashCode());
    }
}

//Run result:
//        true
//        460141958
//        460141958

/*
Hungry Han Style (Static Variable) Method

Advantages: Easy to write, instantiation is done when the class is loaded, and thread synchronization is avoided, so thread safety
 Disadvantages: Lazy loading is not achieved because instantiation is done when the class is loaded.If you haven't used this instance all the time, it's a waste of memory!

Summary: This approach avoids multi-threaded synchronization problems based on the lassLoader class loading mechanism, but the instance property is instantiated when the class is loaded, most of which call the getInstance method in the singleton mode.
     Since the getInstance method is static, calling it will certainly trigger class loading!There are many reasons to trigger class loading, however, and we cannot guarantee that this class will trigger class loading in other ways (such as by calling other static methods)
     Initializing instance s at this time will not have the effect of lazy loading, which may cause a waste of memory!

     Hungry Han style (static variable) can be used but will cause a waste of memory!

     */

Posture 2: Hungry Han 2 (static code block)

package singletonPattern;
//Hungry Han 2 (static code block)

class Singleton2{
    private Singleton2(){

    }

    private static Singleton2 instance;

    static{ //Put the operation of creating a single object in the static code block =============
        instance = new Singleton2();
    }

    public static Singleton2 getInstance(){
        return instance;
    }
}
//Hungry Han Style 2 (static Static Code Block) is actually similar to the first Hungry Han Style (static Variable) method, and has the same advantages and disadvantages!
//The only difference is that you put the operation of creating a single object in the static block of code

Posture 3: Lazy 1 (thread insecure)

package singletonPattern;
//Lazy 1 (thread insecure)
class Singleton3{
    private Singleton3(){

    }

    private static Singleton3 instance;

    public static Singleton3 getInstance(){
        if(instance == null){
            instance=new Singleton3();
        }
        return instance;
    }
}
/*
This lazy (thread insecure) approach has the effect of lazy loading but can only be used on a single thread.
If, under multithreading, one thread enters the if (singleton==null) judgment block and has not executed the sentence that produces the instance, the other thread
 Again, there will be multiple instances, so it is not safe.

Conclusion: Lazy (thread insecure) in the actual development, do not use this way!!Potential danger
*/

Posture 4: Lazy 2 (Thread Safe)

package singletonPattern;
//Lazy 2 (Thread Safe)
class Singleton4{
    private Singleton4(){

    }

    private static Singleton4 instance;

    public static synchronized Singleton4 getInstance(){
        if(instance == null){
            instance=new Singleton4();
        }
        return instance;
    }
}

/*
Lazy 2 (Thread Safe) Mode

Benefits: Thread security
 Disadvantage: Too inefficient to synchronize every call to the getInstance method

Conclusion: The Lazy 2 (Thread Safety) approach is not recommended for development, mainly because it is too inefficient*/

Posture 5: Hungry Han 2 (static code block)

package singletonPattern;
//Lazy 3 Synchronization Code Block (Thread Safe) but does not satisfy the singleton, there will still be multiple instances under multiple threads
class Singleton5{
    private Singleton5(){

    }

    private static Singleton5 instance;

    public static  Singleton5 getInstance(){
        if(instance == null){   //Multiple threads may enter this if block in case of multithreading
            synchronized (Singleton5.class){  //Only one instance will be created here, and although it's safe, it's no longer a singleton
                instance=new Singleton5();
            }
        }
        return instance;
    }
}
/*
Lazy 3 Synchronized Code Block (Thread Safe) but does not satisfy the singleton, there will still be multiple instances

Conclusion: The lazy 3-Sync Code Block (Thread Safe) approach is not used in development, but in fact this singleton design is a bit funny*/

Posture 6: Double Check Single Case

package singletonPattern;
//Double Check Application Instance Mode
class Singleton6{
    private Singleton6(){}

    private static volatile Singleton6 singleton;

    public static Singleton6 getInstance(){
        if(singleton==null){
            synchronized(Singleton6.class){
                if(singleton == null){
                    singleton= new Singleton6();
                }
            }
        }
        return singleton;
    }
}
/*
Double Check Application Instance Method:

Thread Safe, Delayed Loading, High Efficiency

Conclusion: Recommended in development!
*/

At this time, the blogger will have to beep a few sentences, careful children's shoes will find a Volatile keyword, finished, never seen, little white children's shoes panic!

Volatile variables have synchronized visibility but no atomic properties.This means that the thread can automatically discover the latest value of the volatile variable.

This implementation allows threads to safely create instances without too much impact on performance.It is only synchronized the first time an instance is created, and then it is not needed, which speeds up the operation.

Posture 7: Static inner class singleton

package singletonPattern;
//Static static inner class singleton

class Singleton7{
    private Singleton7(){}

    private static volatile Singleton7 instance;

    //Write a static internal class and add a static static instance property to it
    private static class SingletonInstance{
        private static final Singleton7 SINGLETON_7=new Singleton7();
    }

    //
    public static synchronized Singleton7 getInstence(){
        return SingletonInstance.SINGLETON_7;
    }
}
/*
Static Internal Class Singleton
        1,This approach uses a class loading mechanism to ensure that there is only one thread initializing the instance
        2,Clever put the instantiated Singleton operation into the getInstance method, which returns the instantiated Singleton in a static internal class
        3,The static properties of a class are only initialized when it is first loaded, that is, only once. Here, the JVM helps us to keep the thread safe. When the class is initialized, other threads cannot enter.
       
        Advantages: thread-safe, delayed loading with static internal class characteristics, high efficiency
        This static internal class singleton is recommended for development!

static Static internal features:
1,External class loading does not result in internal class loading, guaranteeing lazy loading
*/

This single case, Yichun has to beep two sentences. To understand this single case, you must understand the static internal characteristics, that is, external class loading will not cause internal class loading!

Posture 8: Hungry Han 2 (static code block)

package singletonPattern;
//Use Enumeration

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader;

enum Singleton8{
    INSTANCE;
    public void methodName(){
        System.out.println("test data");
    }
}
/*

Enumeration of enumeration methods:
Recommended writing, simple and efficient.Taking full advantage of the enumeration class's characteristics, only one instance is defined, and enumeration classes naturally support multiple threads.
Enumerations added in JDK1.5 provide the benefits of the singleton mode:
         1,Not only can you avoid multithreaded synchronization problems 
         2,It also prevents deserialization from re-creating new objects

Enumeration singletons are advocated by Josh Bloch, author of Effective java. Conclusion: Recommended!
*/

Of course, you can also test it

public class SingletonDemo8 {
    public static void main(String[] args) {
        Singleton8 instance = Singleton8.INSTANCE;
        Singleton8 instance2 = Singleton8.INSTANCE;
        System.out.println(instance==instance2);

        System.out.println(instance.hashCode());
        System.out.println(instance2.hashCode());

        instance.methodName();
    }
}

Run result:

true
460141958
460141958
 test data

No problem!

Application of singleton mode in JDK source code

Let's take a look at the source code for Runtime and analyze the singleton mode it uses!

/**
 * Every Java application has a single instance of class
 * <code>Runtime</code> that allows the application to interface with
 * the environment in which the application is running. The current
 * runtime can be obtained from the <code>getRuntime</code> method.
 * <p>
 * An application cannot create its own instance of this class.
 *
 * @author  unascribed
 * @see     java.lang.Runtime#getRuntime()
 * @since   JDK1.0
 */
public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}

This should not be difficult to see!If you can't see it, it only means that you really don't understand the singleton mode yet. Actually, I want to say that the singleton mode is the simplest of the 23 design modes, just a lot of writing!At the same time, the interviewer will generally ask the single-case mode, which is already very basic. A little bit more level is to ask you where the single-case mode is used in JDK. Obviously, the Runtime in JDK actually uses the Hungry-Han style single-case!As the comment says, every java application has a Runtime instance.Runtime's singleton mode was created in Hungry Han mode, meaning that when you load this type of file, this instance already exists.

Runtime classes can get JVM system information, or use gc() to free up garbage space, or they can be used to run native programs.

==There is also controller s in spring Mvc that default to singleton mode, parsing.==

Single Case Mode Summary

1. Hungry Han style (static variable) can be used, but not lazy loading will cause a waste of memory!Not recommended for development.
2. The hungry-Han style (static code block) is actually similar to the first hungry-Han style (static variable) method, and its advantages and disadvantages are the same!The only difference is that you put the operation of creating a single object in the static block of code
3. Lazy (thread insecure) has the effect of lazy loading, but can only be used under a single thread.In actual development, do not use this way!!!
4. The Lazy 2 (Thread Safe) method is thread safe but inefficient and needs to be synchronized every time the getInstance method is called.Therefore, it is not recommended in development.5. Lazy 3
The Synchronized Code Block (Thread Safe) approach is not used in development, but the design is actually a bit funny.
6. Double-check application instance mode, thread security, delayed loading, high efficiency.So recommended for development!
7. The static internal class singleton method is thread-safe, uses the static internal class feature to achieve delayed loading, and has high efficiency.This static internal class singleton is recommended for development!
8. Using the enumeration added in JDK1.5 to implement the singleton mode will not only avoid the problem of multithreaded synchronization but also prevent deserialization from re-creating new objects.Enumeration singletons are advocated by Josh Bloch, author of Effective java and recommended for development!

Singleton mode must be used in multi-threaded applications, since servers are basically multi-core.

If this article helps you a little, please give a compliment, thank you~

Finally, if there are any deficiencies or inaccuracies, you are welcome to correct the criticism and appreciate it!If in doubt, please leave a message and reply immediately!

Welcome to pay attention to my public number, discuss technology together, yearn for technology, and pursue technology. Well, you're friends now.

Keywords: Java JDK jvm Spring

Added by Gamic on Tue, 26 Nov 2019 03:58:03 +0200