<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 閱讀(216) 評論(0)  編輯  收藏 所屬分類: Java
    主站蜘蛛池模板: 欧美大尺寸SUV免费| 国产成人yy免费视频| 四虎影在线永久免费观看| 亚洲永久在线观看| 中文字幕无码免费久久99| 亚洲韩国在线一卡二卡| 日韩精品极品视频在线观看免费| 亚洲人成网7777777国产| 一区二区三区免费视频网站| 亚洲国产精品无码久久九九| 麻豆安全免费网址入口| 亚洲不卡AV影片在线播放| 免费国产va在线观看| 免费一区二区三区四区五区| 一级一黄在线观看视频免费| 国产亚洲精品无码拍拍拍色欲| 丁香花在线观看免费观看图片| 亚洲午夜国产精品无码老牛影视| a级毛片在线免费| 亚洲色大成网站www永久一区| 三年片在线观看免费观看大全一| 在线观看亚洲人成网站| 99久久免费国产香蕉麻豆| 亚洲欧美aⅴ在线资源| 亚洲av成人一区二区三区在线观看| av网站免费线看| 内射少妇36P亚洲区| 亚洲成在人线aⅴ免费毛片| 亚洲av无码片vr一区二区三区| 亚洲一区二区三区国产精品| 精品视频在线免费观看| 亚洲三级在线免费观看| 四虎免费永久在线播放| a毛片免费观看完整| 亚洲一区二区影视| 免费大黄网站在线观看| 99久在线国内在线播放免费观看| 国产 亚洲 中文在线 字幕| 亚洲日本韩国在线| 亚洲免费黄色网址| 无套内射无矿码免费看黄|