Java Memory Model: reordering and concurrent locks

后端 未结 4 1142
猫巷女王i
猫巷女王i 2021-02-15 10:22

The java meomry model mandates that synchronize blocks that synchronize on the same monitor enforce a before-after-realtion on the variables modified within those b

4条回答
  •  自闭症患者
    2021-02-15 11:10

    Yanamon, I am not sure you are correct - but for different reasons than the argument you are making.

    The unguardedVariable variable may be re-ordered in thread "a" such that its value is set to 10 after memoryBarrier is set to true.

    "There is no guarantee that operations in one thread will be performed in the order given by the program, as long as the reordering is not detectable within that thread - even if the reordering is apparent to other threads"

    Java Concurrency in Practise, Brian Goetz, p34

    UPDATED: what I said is true in the case of the old memory model. So, if you want write-once-run-anywhere then my argument stands. However, in the new memory model, it is not the case as the semantics surrounding re-ordering of non-volatile variables in the presence of volatile access has become stricter (see http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#volatile).

提交回复
热议问题