Calvin's Tech Space

          成于堅忍,毀于浮躁

             :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
          版本一:
          // 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, 編譯器優(yōu)化了程序指令, 以加快cpu處理速度.
          2, 多核cpu動態(tài)調(diào)整指令順序, 以加快并行運算能力.
          解決一:
          // 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 {
          // 似有靜態(tài)內(nèi)部類, 只有當(dāng)有引用時, 該類才會被裝載
          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
          主站蜘蛛池模板: 特克斯县| 玉树县| 承德县| 邵东县| 清丰县| 中宁县| 夏邑县| 垫江县| 尼木县| 丹巴县| 晋中市| 托里县| 三江| 迁西县| 垣曲县| 搜索| 澄城县| 临沭县| 长宁区| 北京市| 陆丰市| 安图县| 芦山县| 南昌市| 贵德县| 宝丰县| 娱乐| 邓州市| 嵩明县| 瓦房店市| 连城县| 千阳县| 宁蒗| 突泉县| 桦甸市| 金华市| 松溪县| 蒙阴县| 安远县| 屏南县| 兴安盟|