シングルトンパターンの実装方法の比較

遅延初期化(Lazy Initialization): 1. 一回限りの唯一のインスタンスを取得します。
public class Singleton {
    private static Singleton instanceRef;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instanceRef == null) {
            instanceRef = new Singleton();
        }
        return instanceRef;
    }
}
2. 複数スレッド環境下での安全なアクセスを実現します。
public class Singleton {
    private static Singleton instanceRef;
    private static final Object syncLock = new Object();
    private Singleton() {}
    public static Singleton getInstance() {
        synchronized (syncLock) {
            if (instanceRef == null) {
                instanceRef = new Singleton();
            }
        }
        return instanceRef;
    }
}
3. 初回アクセス時にロックを取得し、以降はロックを回避します。
public class Singleton {
    private static Singleton instanceRef;
    private static final Object syncLock = new Object();
    private Singleton() {}
    public static Singleton getInstance() {
        if (instanceRef == null) {
            synchronized (syncLock) {
                if (instanceRef == null) {
                    instanceRef = new Singleton();
                }
            }
        }
        return instanceRef;
    }
}
4. インスタンス生成の非原子性を解消するためにvolatileを適用します。
public class Singleton {
    private volatile static Singleton instanceRef;
    private static final Object syncLock = new Object();
    private Singleton() {}
    public static Singleton getInstance() {
        if (instanceRef == null) {
            synchronized (syncLock) {
                if (instanceRef == null) {
                    instanceRef = new Singleton();
                }
            }
        }
        return instanceRef;
    }
}
積極的初期化(Eager Initialization):
public class Singleton {
    private static final Singleton instance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}
静的内部クラスによる遅延初期化:
public class Singleton {
    private static class Holder {
        private static final Singleton instance = new Singleton();
    }
    private Singleton() {}
    public static Singleton getInstance() {
        return Holder.instance;
    }
}

タグ: Java Singleton Pattern Double-Checked Locking volatile Static Inner Class

6月2日 16:38 投稿