Thread-safe Singleton class
New Singleton class name has renamed to ThreadSafeLazyLoadedIvoryTower and called it from App.java
This commit is contained in:
		@@ -1,10 +1,10 @@
 | 
			
		||||
package com.iluwatar;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * 
 | 
			
		||||
 *
 | 
			
		||||
 * Singleton pattern ensures that the class (IvoryTower) can have only one
 | 
			
		||||
 * existing instance and provides global access to that instance.
 | 
			
		||||
 * 
 | 
			
		||||
 *
 | 
			
		||||
 */
 | 
			
		||||
public class App {
 | 
			
		||||
 | 
			
		||||
@@ -15,5 +15,12 @@ public class App {
 | 
			
		||||
		System.out.println("ivoryTower1=" + ivoryTower1);
 | 
			
		||||
		System.out.println("ivoryTower2=" + ivoryTower2);
 | 
			
		||||
 | 
			
		||||
		ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower1 = ThreadSafeLazyLoadedIvoryTower
 | 
			
		||||
				.getInstance();
 | 
			
		||||
		ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower2 = ThreadSafeLazyLoadedIvoryTower
 | 
			
		||||
				.getInstance();
 | 
			
		||||
		System.out.println("threadSafeIvoryTower1=" + threadSafeIvoryTower1);
 | 
			
		||||
		System.out.println("threadSafeIvoryTower2=" + threadSafeIvoryTower2);
 | 
			
		||||
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -1,18 +0,0 @@
 | 
			
		||||
package com.iluwatar;
 | 
			
		||||
 | 
			
		||||
public class SingletonClass {
 | 
			
		||||
 | 
			
		||||
	private static SingletonClass singletonInstance = null;
 | 
			
		||||
 | 
			
		||||
	public synchronized static SingletonClass getSingleton() {
 | 
			
		||||
		/*
 | 
			
		||||
		 * The instance gets created only when it is called for first time.
 | 
			
		||||
		 * Lazy-loading
 | 
			
		||||
		 */
 | 
			
		||||
		if (singletonInstance == null) {
 | 
			
		||||
			singletonInstance = new SingletonClass();
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		return singletonInstance;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,23 @@
 | 
			
		||||
package com.iluwatar;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 *
 | 
			
		||||
 * Thread-safe Singleton class.
 | 
			
		||||
 *
 | 
			
		||||
 */
 | 
			
		||||
public class ThreadSafeLazyLoadedIvoryTower {
 | 
			
		||||
 | 
			
		||||
	private static ThreadSafeLazyLoadedIvoryTower instance = null;
 | 
			
		||||
 | 
			
		||||
	public synchronized static ThreadSafeLazyLoadedIvoryTower getInstance() {
 | 
			
		||||
		/*
 | 
			
		||||
		 * The instance gets created only when it is called for first time.
 | 
			
		||||
		 * Lazy-loading
 | 
			
		||||
		 */
 | 
			
		||||
		if (instance == null) {
 | 
			
		||||
			instance = new ThreadSafeLazyLoadedIvoryTower();
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		return instance;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user