Sync Singleton to Java 25: split 6 implementations into separate files, consolidated Main.java demo
This commit is contained in:
31
01-creational/singleton/AppConfigDCL.java
Normal file
31
01-creational/singleton/AppConfigDCL.java
Normal file
@@ -0,0 +1,31 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user