Files
design-patterns/01-creational/singleton/AppConfigDCL.java

32 lines
1.0 KiB
Java

package singleton;
public class AppConfigDCL {
// volatile is MANDATORY for DCL to work correctly.
// Without it, the JVM can reorder the writes inside the constructor
// and return a partially-constructed object to a second thread.
private static volatile AppConfigDCL instance;
private AppConfigDCL() { /* load config */ }
public static AppConfigDCL getInstance() {
// First check: no lock, instant return for the 99.99% case
// (instance already created, just return it)
if (instance == null) {
// Lock only when first check says we might need to create
synchronized (AppConfigDCL.class) {
// Second check: re-verify under the lock.
// Another thread might have created the instance between
// our first check and acquiring the lock.
if (instance == null) {
instance = new AppConfigDCL();
}
}
}
return instance;
}
}