在 ArrayBlockingQueue 中,为什么要将 final 成员字段复制到局部 final 变量中?

ArrayBlockingQueue中,所有需要锁的方法在调用 lock()之前将其复制到本地 final变量。

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

当字段 this.lockfinal时,是否有理由将 this.lock复制到局部变量 lock

此外,它还使用 E[]的本地副本,然后再对其采取行动:

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

将 final 字段复制到局部 final 变量有什么理由吗?

3603 次浏览

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:

  • the compiler can't easily prove that a final field does not change within a method (due to reflection / serialization etc.)
  • most current compilers actually don't try and would therefore have to reload the final field everytime it is used which could lead to a cache miss or a page fault
  • storing it in a local variable forces the JVM to perform only one load