📙
Design Pattern
  • Introduction
  • 0. About Design Pattern
  • 1. Singleton
  • 1.1 Eager Singleton (a.k.a Pessimistic Lock Singleton)
  • 1.2 Lazy Singleton (a.k.a Optimistic Lock Singleton)
  • 1.3 理解Singleton
  • 1.4 Cache Singleton
  • 1.5 Extend Singleton
  • 1.6 Double Check and Lock Singleton
  • 1.7 Lazy Initialization Holder Class
  • 1.8 Enum Singleton
  • 1.9 Conclusion
  • 2. Factory
  • 2.1 Simple Factory
  • 2.2 Factory
  • 2.3 Abstract Factory
  • 2.4 Conclusion
Powered by GitBook
On this page

Was this helpful?

1.6 Double Check and Lock Singleton

根據1.3節提到的雙重鎖定機制, 這邊附上範例:

package idv.design.pattern.singleton.doublecheck;

/**
 * @author Carl Lu
 */
public class Singleton {

    /*
     * With volatile, the variable value will not be cached by local thread,
     * all the read/write operations are against the shared memory so that
     * we can ensure threads can handle the variable properly.
     *
     * This pattern is also called "DCL".
     */
    private volatile static Singleton instance = null;

    private Singleton() {

    }

    public static Singleton getInstance() {
        // First check
        if (instance == null) {
            synchronized (Singleton.class) {
                // Second check
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

}
Previous1.5 Extend SingletonNext1.7 Lazy Initialization Holder Class

Last updated 5 years ago

Was this helpful?

原始碼

其實, 這邊使用volatile背後的意義, 遠比這裡表面上看到的要來得複雜, 我寫在, 有興趣的話可以看看.

點我
這邊