Singleton Pattern is a software design pattern which restrict only one class instance.

Below is an example implementation in java.

public class MySingleton{
    private static MySingleton instance = new MySingleton();
    private MySingleton(){
    }

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

a private static instance variable.

a private constructor. So nobody can use new to create instance outside of the class.

a public static getInstance() method.

But above case, it's not thread safe. Let's make some changes.

public class MySingleton{
    private static volatile MySingleton instance = new MySingleton();
    private MySingleton(){
    }

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

First I added volatile keyword for instance variable to make it visiable in mutilthread environment.

Then I added synchronized for getInstance() method.

Now let's optimize the performance.

public class MySingleton{
    private static volatile MySingleton instance = null;
    private MySingleton(){
        if(instance!=null){
            throw new RuntimeException("please use getInstance method!");
        }
    }

    public static  MySingleton getInstance(){
        if(instance==null){
            synchronized(MySingleton.class){
                if(instance==null){
                    instance = new MySingleton();
                }
            }
        }
    
        return instance;
    }
}

I synchronized the block of code which create the instance instead of synchronized the whole method.

I used lazy loading concept to create the instance only when somebody call getInstance() method.