提交 3033e4c9 编写于 作者: I Ilkka Seppälä

Improve lazy loaded Singleton example

上级 e68beb40
......@@ -27,15 +27,13 @@ package com.iluwatar.singleton;
* <p>Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization
* mechanism.</p>
*
* <p>Note: if created by reflection then a singleton will not be created but multiple options
* in the same classloader</p>
*/
public final class ThreadSafeLazyLoadedIvoryTower {
private static ThreadSafeLazyLoadedIvoryTower instance;
private static volatile ThreadSafeLazyLoadedIvoryTower instance;
private ThreadSafeLazyLoadedIvoryTower() {
// protect against instantiation via reflection
// Protect against instantiation via reflection
if (instance == null) {
instance = this;
} else {
......@@ -44,13 +42,16 @@ public final class ThreadSafeLazyLoadedIvoryTower {
}
/**
* The instance gets created only when it is called for first time. Lazy-loading
* The instance doesn't get created until the method is called for the first time
*/
public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {
if (instance == null) {
instance = new ThreadSafeLazyLoadedIvoryTower();
synchronized (ThreadSafeLazyLoadedIvoryTower.class) {
if (instance == null) {
instance = new ThreadSafeLazyLoadedIvoryTower();
}
}
}
return instance;
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册