/** * declared as volatile to ensure atomic access by multiple threads. */ privatestaticvolatile ThreadSafeLazyLoadedSingleton instance;
/** * Private constructor to prevent instantiation from outside the class. */ privateThreadSafeLazyLoadedSingleton(){ // Protect against instantiation via reflection if (instance != null) { thrownew IllegalStateException("Already initialized."); } }
/** * The instance doesn't get created until the method is called for the first time. */ publicstaticsynchronized ThreadSafeLazyLoadedSingleton getInstance(){ if (instance == null) { instance = new ThreadSafeLazyLoadedSingleton(); } return instance; }
/** * declared as volatile to ensure atomic access by multiple threads. */ privatestaticvolatile ThreadSafeDoubleCheckSingleton instance;
/** * Private constructor to prevent instantiation from outside the class. */ privateThreadSafeDoubleCheckSingleton(){ // Protect against instantiation via reflection if (instance != null) { thrownew IllegalStateException("Already initialized."); } }
/** * To be called by user to obtain instance of the class. */ publicstatic ThreadSafeDoubleCheckSingleton getInstance(){ // local variable increases performance by 25 percent ThreadSafeDoubleCheckSingleton result = instance; // Check if singleton instance is initialized. if (instance == null) { synchronized (ThreadSafeDoubleCheckSingleton.class) { result = instance; if (result == null) { result = new ThreadSafeDoubleCheckSingleton(); instance = result; } } } return result; }
/** * Private constructor to prevent instantiation from outside the class. */ privateStaticInnerClassSingleton(){
}
/** * The InstanceHolder is a static inner class, and it holds the Singleton instance. * It is not loaded into memory until the getInstance() method is called. */ privatestaticclassInstanceHolder{ privatestaticfinal StaticInnerClassSingleton INSTANCE = new StaticInnerClassSingleton(); }
/** * When this method is called, the InstanceHolder is loaded into memory * and creates the Singleton instance. This method provides a global access point * for the singleton instance. */ publicstatic StaticInnerClassSingleton getInstance(){ return InstanceHolder.INSTANCE; }