What are the lazy mode and hungry mode in the singleton mode?

1. Lazy mode:

As the name suggests, he is a sluggard who is unwilling to move. Whenever he needed to eat, he would start thinking of ways to get some food.
That is, the lazy style will not be instantiated at the beginning, and will be instantiated whenever new is used.

2. Hungry Man Mode:

As the name suggests, he is a hungry man. He is very diligent but is afraid of starving himself. He always prepares the food first, and when he needs to eat, he can eat it at any time without having to get food at last minute.
That is, Hungry Style has been instantiated when the class is loaded at the beginning, and a singleton object has been created, and it can be used later.

3. Lazy code implementation:

public class Singleton {
 //默认不会实例化,什么时候用就什么时候new
    private static Singleton instance = null;
    private Singleton(){

    }
    public static synchronized Singleton getInstance(){
        if(instance == null){
   //什么时候用就什么时候new
            instance = new Singleton();
        }
        return instance;
    }
}

4. Hungry-Chinese code implementation:

public class Singleton {
 //一开始类加载的时候就实例化,创建单实例对象
    private static Singleton instance = new Singleton();
    private Singleton(){

    }
    public static Singleton getInstance(){
        return instance;
    }
}

5. The security and performance differences between the lazy style and the hungry style:
(1) Thread safety: The hungry style has been instantiated before the thread appears, so the hungry style must be thread safe. Lazy loading will only go to the new instance when it is used. So when you go to new, it is a dynamic process and is implemented in a method, such as:

public static synchronized Singleton getInstance() {
    if(instance == null){
    //什么时候用就什么时候new
        instance = new Singleton();
     }
}

If there are multiple threads accessing this instance at this time, and the instance does not exist yet and is still new, it will enter the method, and as many instances will be new as there are threads. A method can only return one instance, so which one will be returned in the end? Will it cover many new instances? This situation can of course be solved by adding a synchronization lock to prevent this situation from happening.

(2) Execution efficiency: Hungry style does not add any locks, so the execution efficiency is relatively high. The lazy man style generally adds a synchronization lock when used, and the efficiency is worse than the hungry man style.
(3) Memory usage: Hungry style is instantiated when the class is loaded at the beginning. It will be instantiated whether it is used or not, so it will occupy space and waste memory. The lazy style can be instantiated whenever it is used, without wasting memory.

Guess you like

Origin blog.csdn.net/wangguoqing_it/article/details/125617461