Singleton design pattern

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

[Wikipedia]

Intro

In this example we will try to create two instances of the singleton type. Each instance will recieve it's own id( System.identityHashCode) . We will compate both id's : if we will get two diffrenet id it means we created two instances, else we created just one instance and we keep getting the same one at each getInstance() calll. 

Singleton

public class Singleton {
    private static Singleton onlyInstance = null;

    private Singleton(){}
    public static Singleton getInstance() {
        /* If the instance isn't null-  it means we already created an instance, so we will return the old one.
           if it is null- this is the first creation of onlyInstance, so we create it.
           This implementation is Thread Safe.*/
            synchronized(Singleton.class){
                if(onlyInstance == null) {
                    onlyInstance = new Singleton();
                }
            }
        return onlyInstance;
    }
}

Main


    /**
    In this example we will try to create two instances of the singleton type.
    Each instance will recieve it's own id( System.identityHashCode) .
    We will compate both id's : if we will get two diffrenet id it means we created two instances, 
    else we created just one instance and we keep getting the same one at each getInstance() calll. 
    
    **/
    public class main {
    
    private static void doSomeStuff() {
        System.out.println("Doing some stuff....");
        try {
            Thread.currentThread();
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String []args)
    {
        System.out.println("Creating first singleton...");
        Singleton singleton1= Singleton.getInstance();
        System.out.println("1st Instance ID: " + System.identityHashCode(singleton1));
        doSomeStuff();
        System.out.println("Trying to create another instance of the singleton...");
        Singleton singleton2= Singleton.getInstance();
        System.out.println("2nd Instance ID: " + System.identityHashCode(singleton2));
        System.out.println("The same id = the same instance of singleton.");
    }
}

Running Example

Creating first singleton...
1st Instance ID: 356573597
Doing some stuff....
Trying to create another instance of the singleton...
2nd Instance ID: 356573597
The same id = the same instance of singleton.