Double checked locking Article

后端 未结 10 676
别那么骄傲
别那么骄傲 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:01

    Following the John Skeet Recommendation:

    However, to go deeper into the subject I'd recommend Bill Pugh's article. And then never attempt it :)

    And here is the key for the second sync block:

    This code puts construction of the Helper object inside an inner synchronized block. The intuitive idea here is that there should be a memory barrier at the point where synchronization is released, and that should prevent the reordering of the initialization of the Helper object and the assignment to the field helper.

    So basically, with the Inner sync block, we are trying to "cheat" the JMM creating the Instance inside the sync block, to force the JMM to execute that allocation before the sync block finished. But the problem here is that the JMM is heading us up and is moving the assigment that is before the sync block inside the sync block, moving our problem back to the beginnig.

    This is what i understood from those articles, really interesting and once more thanks for the replies.

提交回复
热议问题