Double checked locking Article

后端 未结 10 660
别那么骄傲
别那么骄傲 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 21:00

    The article refers to the pre-5.0 Java memory model (JMM). Under that model leaving a synchronised block forced writes out to main memory. So it appears to be an attempt to make sure that the Singleton object is pushed out before the reference to it. However, it doesn't quite work because the write to instance can be moved up into the block - the roach motel.

    However, the pre-5.0 model was never correctly implemented. 1.4 should follow the 5.0 model. Classes are initialised lazily, so you might as well just write

    public static final Singleton instance = new Singleton();
    

    Or better, don't use singletons for they are evil.

提交回复
热议问题