Java Memory Model: reordering and concurrent locks

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

    Reading and writing volatile variables now enforces happens before and happens after operation ordering. Writing to a volatile variable has the same effect as releasing a monitor and reading a variable has the effect as acquiring a monitor. The following example makes it a little more clear:

    volatile boolean memoryBarrier = false;
    int unguardedValue = 0;
    
    //thread a:
    unguardedValue = 10;
    memoryBarrier = true;
    
    // thread b
    if (memoryBarrier) {
      // unguardedValue is guaranteed to be read as 10;
    }
    

    But that all being said the sample code you provided did not look like it was really using the ReentrantLock as it was designed to be used.

    1. Surrounding the use of a Lock with the the Java's built in syncronized keyword effectively makes access to the lock already single threaded so it doesn't give the Lock a chance to do any real work.
    2. Acquiring a releasing a Lock should be done following the pattern below, this is outlined in the java docs of Lock

    lock.readLock().lock();
    try {
      // Do work
    } finally {
      lock.readLock.unlock();
    }
    

提交回复
热议问题