views:

141

answers:

2

In ArrayBlockingQueue, any method that requires lock will get set 'final' local variable before calling 'lock()'.

public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        if (count == items.length)
            return false;
        else {
            insert(e);
            return true;
        }
    } finally {
        lock.unlock();
    }
}

Is there any reason to set a local variable 'lock' from 'this.lock' when field 'this.lock' is final also.

Additionally, it also set local variable of E[] before acting on.

private E extract() {
    final E[] items = this.items;
    E x = items[takeIndex];
    items[takeIndex] = null;
    takeIndex = inc(takeIndex);
    --count;
    notFull.signal();
    return x;
}

Is there any reason for copying to local final variable?

+7  A: 

It's an extreme optimization Doug Lea, the author of the class, likes to use. Here's a post on a recent thread on the core-libs-dev mailing list about this exact subject which answers your question pretty well.

from the post:

...copying to locals produces the smallest bytecode, and for low-level code it's nice to write code that's a little closer to the machine

ColinD
Strong emphasis on "extreme"! This is not a general-purpose good programming practice that everyone should be emulating.
Kevin Bourrillion
Random FYI: in some other cases when you see this done, it's because the field in question is volatile, and the method needs to make sure it's got a single consistent value or reference for it throughout.
Kevin Bourrillion
+2  A: 

This is a great question, I was looking at ArrayBlockingQueue and wondered the same thing myself. I have a more in depth answer about why the byte code is more compact here for anyone who is curious:

http://kingsbery.net/2010/06/02/bytecode-analysis-of-arrayblockingqueue/

James Kingsbery