Assign Java Lock variable before use. What for?

In many Java sources (e.g. 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 eventually), but my question is: why assign a local lock variable before using it? Why is this instead of the next?

final ReentrantLock lock = new ReentrantLock();

public void putLast(E e) throws InterruptedException {
    this.lock.lock();
    try {
       // do stuff
    } finally {
        lock.unlock();
    }
}

Will it affect optimization? Can the first example prevent lock escalation?

EDIT after comments . Please do not add an answer if you really do not know why this is so. This is from a Java source, the @author tag is Doug Lea, so I'm sure it is there for some reason. Do not indicate that the code is simply equivalent.

thank

+5
5

: . , , , : , , .

, : .

+2

, , :

  • LinkedBlockingDeque ( JDK 1.6) " ".
  • CopyOnWriteArrayList ( JDK 1.5) " ".

java.util.concurrent, , .

, lock final. , JVM (. JLS).

: .

, Dough Lea ( ). , , " " - , java.util.concurrent JDK , JVM . , :

public void op(){
    ReentrantLock lock = getLock();
    lock.lock();
    try {
        realOp();
    } finally {
        lock.unlock();
    }
}

getLock() .

+2

Hotspot .

, , , , 1%, , - , . .

, / .

, . .

+1

, , JRE .

General recommendations still should not bother local ones. This is only because performance is really, really important in the specific code used by many people.

0
source

All Articles