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;
    }
}原始碼點我
其實, 這邊使用volatile背後的意義, 遠比這裡表面上看到的要來得複雜, 我寫在這邊, 有興趣的話可以看看.
Last updated
Was this helpful?