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 閱讀(226) 評論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 广汉市| 中阳县| 新绛县| 阳曲县| 巴楚县| 公安县| 讷河市| 大理市| 木里| 科技| 门源| 河北区| 星座| 湘西| 义乌市| 额尔古纳市| 岳西县| 绥中县| 宜兴市| 罗城| 峨眉山市| 荥阳市| 日照市| 图们市| 连云港市| 湾仔区| 名山县| 福鼎市| 皋兰县| 嵊州市| 福贡县| 迁安市| 远安县| 察雅县| 阿巴嘎旗| 林州市| 南溪县| 泸水县| 公主岭市| 宝山区| 石台县|