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