Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy initialization Singleton class with volatile variable [duplicate]

I came across a singleton class {lazy initialization}. The code is as below

// Singleton reference for this class
    private static volatile FileProperties INSTANCE = null; 

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

My question is what is the benefit we are getting by making INSTANCE as volatile Since we already taking care of thread safety by synchronized. Is there any benefit of volatile in this scenario ?

like image 348
sorabh solanki Avatar asked Feb 11 '26 23:02

sorabh solanki


1 Answers

That is because double-checked locking without volatile is not thread-safe in Java.

The simplest way to make thread-safe lazy-init singleton is to create class holder as follows:

public class SomeClass {
    private static class SomeClassHolder {
        public static final SomeClass INSTANCE = new SomeClass();
    }

    public static SomeClass getInstance() {
       return SomeClassHolder.INSTANCE;
    } 

    private SomeClass() {}

}

That part of code, because of JVM behavior will load SomeClassHolder and create an instance of SomeClass on first usage of getInstance() (and not when SomeClass is loaded by classloader).

You don't need to use any synchronization at all!! Because JVM is doing it for you.

like image 170
Michal Borek Avatar answered Feb 14 '26 16:02

Michal Borek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!