1

Under what circumstances, we need to use the lazy singleton mode. It seems that in the process of use, we load a class to use its properties or methods, then we must create its instance at this time, so there is no difference between a hungry man and a lazy man. In what scenario do we need to load It seems that a class is always loaded the first time it is used

My question is : Under what circumstances, a singleton class will be loaded by jvm but not used. It seems that jvm always loads this class when it is used for the first time

class Main{
    public static void main(String[] args) {
        Singleton instance=Singleton.getInstance();
        Singleton1 singleton1=Singleton1.getInstance();
    }
}
class Singleton1{
    private Singleton1(){}
    private volatile static Singleton1 instance=null;
    public static Singleton1 getInstance(){
        if(instance==null){
            synchronized (Singleton1.class){
                if(instance==null){
                    instance=new Singleton1();
                }
            }
        }
        return instance;
    }
}
class Singleton{
    private Singleton(){}
    private static Singleton instance=new Singleton();
    public static Singleton getInstance(){
        return instance;
    }
}

There seems to be no difference between the two

Hope to get some lazy singleton application scenarios

jcli
  • 21
  • 1
  • @paulsm4 `Singleton` doesn't incur any overhead either until it's used. – shmosel Aug 04 '23 at 05:28
  • @shmosel yes, my problem is here – jcli Aug 04 '23 at 06:20
  • @jcli:: as shmosel pointed out: 1) Neither example incurs any runtime overhead unless/until the app actually tries to *access* the class, 2) Your "Singleton1" example (the style I've always used) has a potential race condition if `Singleton1.getInstance()` is called from multiple concurrent threads. Here's a good discussion of different alternatives: https://www.digitalocean.com/community/tutorials/java-singleton-design-pattern-best-practices-examples – paulsm4 Aug 04 '23 at 18:52
  • @paulsm4:: In fact, what I want to know is when using Singleton1 is better than Singleton and when using Singleton is better – jcli Aug 05 '23 at 07:40
  • The link I cited, [Java Singleton Design Pattern Best Practices with Examples](https://www.digitalocean.com/community/tutorials/java-singleton-design-pattern-best-practices-examples), actually gives *eight* different alternatives for implementing a singleton in Java, And discusses the pros/cons of each. Personally, whenever it's applicable, I prefer "lazy initialization" (`if instance == null...`), without "synchronized" (unnecessary overhead if not multithreaded). – paulsm4 Aug 05 '23 at 16:29

0 Answers0