Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it doesn't use the instance field directly, but assigns it to a local variable? [duplicate]

Tags:

java

I'm reading the source of java.util.concurrent.ArrayBlockingQueue, and found some code I don't understand:

private final ReentrantLock 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();
    }
}

Notice this line:

final ReentrantLock lock = this.lock;

Why it doesn't use this.lock directly, but assigns it to a local variable?

like image 747
Freewind Avatar asked Oct 30 '11 07:10

Freewind


2 Answers

Could it be for optimization purposes?

Possibly a local variable could more easily be directly allocated to a register with a JIT compiler.

At least in Android, for the first versions of the API, accessing a local variable was cheaper than accessing an instance variable (can't speak for newer versions). It could be that plain Java is the same, and in some cases it makes sense to use a local.

Actually, found a thread confirming this here. Extract:

It's a coding style made popular by Doug Lea. It's an extreme optimization that probably isn't necessary; you can expect the JIT to make the same optimizations. (you can try to check the machine code yourself!) Nevertheless, 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.

like image 178
JRL Avatar answered Oct 04 '22 16:10

JRL


Since it's just copying the reference and the lock is on the Object instead, and the Object is the same, it shouldn't matter.

The instance variable lock is also declared final, so really, I don't see any point in doing a reference copy.

As JRL pointed out is an optimization, but it's really such a tiny micro-optimization, that I still don't see much point doing it, especially for just one read.

like image 41
stivlo Avatar answered Oct 04 '22 15:10

stivlo