Search code examples
javamultithreadingsynchronizedvolatile

Synchronized block in Singleton Pattern (Java)


I have a question regarding a thread-safe Singleton pattern I found on Wikipedia.

public final class Singleton {

    private static volatile Singleton instance = null;

    private Singleton() {}

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

        return instance;
    }
}

If the synchronized block wasn't synchronized, would it be possible for 2 threads to create 2 objects simultaneously?

I need to explain the usage of "synchronized" for an assignment.

Thanks and best regards


Solution

  • If it wasn't synchronized, you could indeed have 2 threads create 2 objects.

    • T1: checks if instance is null => yes! => continues to next line
    • T2: checks if instance is null => yes! => continues to next line
    • T1: creates object
    • T2: creates object

    While using synchronized, only 1 thread can enter the synchronized blocked at a time.

    • T1: checks if instance is null => yes! => continues to next line
    • T1: creates object
    • T2: checks if instance is null => no! => skips block

    Edit:

    It is worth noting that the null check inside of the synchronized block is actually very important - otherwise it would be possible to create 2 objects as well. – Amongalen (in comments)

    Another way to achieve a Singleton pattern is the following. Only use this pattern if creating the object isn't a big problem to do as soon as the application starts:

    public final class Singleton {
    
        private static Singleton instance = new Singleton();
    
        private Singleton() {}
    
        public static Singleton getInstance() {
            return instance;
        }
    }