Sync Singleton to Java 25: split 6 implementations into separate files, consolidated Main.java demo

This commit is contained in:
2026-06-23 11:11:02 +05:30
parent 2fbf89875b
commit 4b6a02f396
9 changed files with 176 additions and 23 deletions

View 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;
}
}