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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With