<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    Calvin's Tech Space

    成于堅忍,毀于浮躁

       :: 首頁 :: 聯系 :: 聚合  :: 管理
    版本一:
    // Single threaded version
    class Foo { private static Helper helper = null; private Helper(){ } public static Helper getHelper() { if (helper == null) helper = new Helper(); return helper; } // other functions and members... }
    版本二:
    // Correct but possibly expensive multithreaded version
    class Foo { private Helper helper = null; public synchronized Helper getHelper() { if (helper == null) helper = new Helper(); return helper; } // other functions and members... }
    版本三(DCL):
    // Broken multithreaded version
    // "Double-Checked Locking" idiom class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized(this) { if (helper == null) { helper = new Helper(); } } } return helper; } // other functions and members... }
    DCL還是會失效,最重要的2個原因如下:
    1, 編譯器優化了程序指令, 以加快cpu處理速度.
    2, 多核cpu動態調整指令順序, 以加快并行運算能力.
    解決一:
    // Works with acquire/release semantics for volatile
    // Broken under Java 1.4 and earlier semantics for volatile
    class Foo {
    private volatile Helper helper = null;
    public Helper getHelper() {
    if (helper == null) {
    synchronized(this) {
    if (helper == null)
    helper = new Helper();
    }
    }
    return helper;
    }
    // other functions and members...
    }
    
    解決二:
    public class Foo {
    // 似有靜態內部類, 只有當有引用時, 該類才會被裝載
    private static class LazyFoo {
    public static Foo foo = new Foo();
    }
     
    public static Foo getInstance() {
    return LazyFoo.foo;
    }
    }
     
    參考:
    http://kenwublog.com/explain-java-memory-model-in-detail(涉及了很多Java底層的東西,值得一看)
    http://en.wikipedia.org/wiki/Double-checked_locking
    posted on 2010-01-03 19:55 calvin 閱讀(223) 評論(0)  編輯  收藏 所屬分類: Java
    主站蜘蛛池模板: 亚洲熟妇av一区二区三区| 在线a亚洲v天堂网2018| 亚洲成人午夜在线| 99精品免费视品| 九九久久精品国产免费看小说| 精品国产一区二区三区免费看| 亚洲精品人成无码中文毛片| 亚洲精品视频在线| 久久久国产精品无码免费专区| 久久亚洲伊人中字综合精品| 最好免费观看高清在线| 亚洲视频在线免费观看| 久久精品无码专区免费青青 | 亚洲精品A在线观看| 深夜A级毛片视频免费| 曰韩亚洲av人人夜夜澡人人爽 | 国产美女被遭强高潮免费网站| 亚洲国产精品网站在线播放| 国产免费怕怕免费视频观看| 一区二区三区免费高清视频| 久久精品国产亚洲| 麻豆最新国产剧情AV原创免费| 亚洲精品日韩一区二区小说| 亚洲国产精品成人| 久别的草原电视剧免费观看| 亚洲女人18毛片水真多| 日韩一区二区免费视频| 国产VA免费精品高清在线| 亚洲AV日韩AV天堂一区二区三区| 黄在线观看www免费看| 色天使色婷婷在线影院亚洲 | 免费大学生国产在线观看p| 男人和女人高潮免费网站| 国产aⅴ无码专区亚洲av| 成年人网站免费视频| 国产亚洲日韩在线a不卡| 亚洲国产精品va在线播放| 免费A级毛片无码免费视| 亚洲另类自拍丝袜第1页| 国产精品免费大片| 亚洲午夜无码久久|