// Eager singleton
EagerSingleton eager1 = EagerSingleton.getInstance();
EagerSingleton eager2 = EagerSingleton.getInstance();
System.out.println(eager1 == eager2); // true - same instance
// Lazy singleton (not thread-safe)
LazySingleton lazy1 = LazySingleton.getInstance();
LazySingleton lazy2 = LazySingleton.getInstance();
System.out.println(lazy1 == lazy2); // true - same instance
// Thread-safe singleton
SynchronizedSingleton sync1 = SynchronizedSingleton.getInstance();
SynchronizedSingleton sync2 = SynchronizedSingleton.getInstance();
System.out.println(sync1 == sync2); // true
// Double-checked singleton
DoubleCheckedSingleton dcs1 = DoubleCheckedSingleton.getInstance();
DoubleCheckedSingleton dcs2 = DoubleCheckedSingleton.getInstance();
System.out.println(dcs1 == dcs2); // true
// Bill Pugh singleton (recommended)
BillPughSingleton bp1 = BillPughSingleton.getInstance();
BillPughSingleton bp2 = BillPughSingleton.getInstance();
System.out.println(bp1 == bp2); // true
// Enum singleton (simplest)
EnumSingleton enum1 = EnumSingleton.INSTANCE;
EnumSingleton enum2 = EnumSingleton.INSTANCE;
System.out.println(enum1 == enum2); // true
enum1.doSomething();
// In multithreaded environment
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
executor.submit(() -> {
BillPughSingleton instance = BillPughSingleton.getInstance();
System.out.println("Thread: " + Thread.currentThread().getName() + ", Instance: " + instance);
});
}
executor.shutdown();