In ArrayBlockingQueue
, all the methods that require the lock copy it to a local final
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 copy this.lock
to a local variable lock
when the field this.lock
is final
?
Additionally, it also uses a local copy of E[]
before acting on it:
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 a final field to a local final variable?
There are several ways to declare a reference variable: ClassName variableName; This declares a reference variable and declares the class of the object it will later refer to. No object is created.
Reference variable is used to point object/values. 2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java.
Reference variables can be declared as static variables, instance variables, method parameters, or local variables. A reference variable that is declared as final can't never be reassigned to refer to a different object. The data within the object can be modified, but the reference variable cannot be changed.
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
This thread gives some answers. In substance:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With