Double checked locking Article

后端 未结 10 672
别那么骄傲
别那么骄傲 2020-12-09 20:06

I was reading this article about \"Double-Checked locking\" and out of the main topic of the article I was wondering why at some point of the article the author uses the nex

10条回答
  •  我在风中等你
    2020-12-09 20:55

    For Java 5 and better there is actually a doublechecked variant that can be better than synchronizing the whole accessor. This is also mentioned in the Double-Checked Locking Declaration :

    class Foo {
        private volatile Helper helper = null;
        public Helper getHelper() {
            if (helper == null) {
                synchronized(this) {
                    if (helper == null)
                        helper = new Helper();
                }
            }
            return helper;
        }
    }
    

    The key difference here is the use of volatile in the variable declaration - otherwise it does not work, and it does not work in Java 1.4 or less, anyway.

提交回复
热议问题