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
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.
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.Lock
should be done following the pattern below, this is outlined in the java docs of Locklock.readLock().lock();
try {
// Do work
} finally {
lock.readLock.unlock();
}