Java Memory Model: reordering and concurrent locks

后端 未结 4 1135
猫巷女王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:17

    Beyond the question of what the semantics of the memory model guarantees, I think there are a few problems with the code you are posting.

    1. You are synchronizing twice on the same lock - this is unnecessary. When using a Lock implementation, you don't have need to use the synchronized block.
    2. The standard idiom for using a Lock is to do so in a try-finally block to prevent accidental unlocking of the lock (since the lock is not automatically released when entering whatever block you are in, as with the synchronized block).

    You should be using a Lock with something resembling:

    lock.lock();
    try {
        //do stuff
    }
    finally { 
        lock.unlock();
    }
    

提交回复
热议问题