In a lot of of the Java source, (for example LinkedBlockingDeque
) I see things like this;
final ReentrantLock lock = new ReentrantLock();
public void putLast(E e) throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// do stuff
} finally {
lock.unlock();
}
}
I understand the basic pattern (lock, unlock in finally) but my question is why make an assignment to a locally scoped Lock variable before using it? Why do this instead of the following?
final ReentrantLock lock = new ReentrantLock();
public void putLast(E e) throws InterruptedException {
this.lock.lock();
try {
// do stuff
} finally {
lock.unlock();
}
}
Would it affect optimisations? Could the first example prevent lock coarsening?
EDIT after comments: Please don't add an answer if you don't really know why this is the case. This is from the Java source, the @author tag is Doug Lea so I'm pretty sure it's there for a reason. Please don't point out that the code is simply equivalent.
Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…