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
2.1 Benefits of ReentrantLock in Java 1) Ability to lock interruptibly. 2) Ability to timeout while waiting for lock. 3) Power to create fair lock. 4) API to get list of waiting thread for lock.
Java lock acts as thread synchronization mechanisms that are similar to the synchronized blocks. After some time, a new locking mechanism was introduced. It is very flexible and provides more options in comparison to the Synchronized block.
Use the synchronized keyword. Using the synchronized keyword on the methods will require threads to obtain a lock on the instance of sample . Thus, if any one thread is in newmsg() , no other thread will be able to get a lock on the instance of sample , even if it were trying to invoke getmsg() .
When you assign to local variable in method, compiler can do some optimizations. see In ArrayBlockingQueue, why copy final member field into local final variable?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With