Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Lock variable assignment before use. Why?

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

like image 938
Toby Avatar asked Nov 05 '11 11:11

Toby


People also ask

Why is ReentrantLock needed?

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.

What is locking in Java?

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.

How do you lock a variable in Java?

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() .


1 Answers

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?

like image 160
Sergey Gazaryan Avatar answered Nov 15 '22 00:11

Sergey Gazaryan