Written test summary series: write a single case! Lazy loading, thread safe, high performance

Write a singleton! Lazy loading, thread safe, high performance

The lazy loading mentioned above, the so-called lazy loading means that the corresponding class is loaded when the object is actually used, otherwise it is just a declaration, and no resources are actually spent to initialize the object.

First come the most basic and easiest

public class Singleton {
    
      
    private Singleton() {
    
    }  //私有的构造函数
    private static Singleton instance = null;  
    public static Singleton getInstance() {
    
      
        if(instance == null) {
    
      
            instance = new Singleton();  
        }  
        return instance;  
    }  
}

What is its problem?

In single thread, it is fine, but in multithread, if multiple threads call getInstance at the same time, new may be called multiple times, which will cause problems.

How to deal with it?

Think of using locks, synchronized and other methods

Correct double check lock

First determine whether the object has been initialized, and then decide whether to lock.

public class Singleton {
    
    
    private volatile static Singleton uniqueSingleton;

    private Singleton() {
    
    
    }

    public Singleton getInstance() {
    
    
        if (null == uniqueSingleton) {
    
    
            synchronized (Singleton.class) {
    
    
                if (null == uniqueSingleton) {
    
    
                    uniqueSingleton = new Singleton();
                }
            }
        }
        return uniqueSingleton;
    }
}

Static inner class method

We can put the Singleton instance in a static inner class, which avoids the creation of objects when the Singleton class is loaded, and since the static inner class will only be loaded once, this writing method is also thread-safe

public class Singleton {
    
    
    private static class Holder {
    
    
        private static Singleton singleton = new Singleton();
    }
    
    private Singleton(){
    
    }
        
    public static Singleton getSingleton(){
    
    
        return Holder.singleton;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43337081/article/details/109086603