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?
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: