0

While reading the source code of ArrayBlockingQueue, I found below code:

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        try {
            while (count == 0)
                notEmpty.await();
        } catch (InterruptedException ie) {
            notEmpty.signal(); // propagate to non-interrupted thread
            throw ie;
        }
        E x = extract();
        return x;
    } finally {
        lock.unlock();
    }
}

why not use the code

public E take() throws InterruptedException {
     lock.lockInterruptibly();
    try {
        try {
            while (count == 0)
                notEmpty.await();
        } catch (InterruptedException ie) {
            notEmpty.signal(); // propagate to non-interrupted thread
            throw ie;
        }
        E x = extract();
        return x;
    } finally {
        lock.unlock();
    }
}

what's the Benefit of the line code :final ReentrantLock lock = this.lock;

Anirudha
  • 32,393
  • 7
  • 68
  • 89
fuyou001
  • 1,594
  • 4
  • 16
  • 27

1 Answers1

0

This idea was popularized by Doug Lea - I think that the original idea was that the JVM could possibly perform some performance related optimization when there was a final local variable used.

Check out this thread from the OpenJDK thread which discusses this very question

Edit:

A little research threw up these two related questions on stack:

In ArrayBlockingQueue, why copy final member field into local final variable?

Java Lock variable assignment before use. Why?

Community
  • 1
  • 1
Sean Landsman
  • 7,033
  • 2
  • 29
  • 33
  • This is not the best reference - [this other thread](http://cs.oswego.edu/pipermail/concurrency-interest/2011-January/007703.html) is more informative. – assylias Apr 13 '13 at 13:37