# 1.6 Double Check and Lock Singleton

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

```java
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;
    }

}
```

原始碼[點我](https://github.com/yotsuba1022/design-pattern/blob/master/src/main/java/idv/design/pattern/singleton/doublecheck/Singleton.java)

其實, 這邊使用volatile背後的意義, 遠比這裡表面上看到的要來得複雜, 我寫在[這邊](https://yotsuba1022.gitbooks.io/about-java-memory-model-jmm-a-k-a-jsr-133/content/1111111.html), 有興趣的話可以看看.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://clu.gitbook.io/design-pattern/16-double-check-and-lock-singleton.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
