gpt4 book ai didi

java - 在ArrayBlockingQueue中,为什么将final成员字段复制到本地final变量中?

转载 作者:行者123 更新时间:2023-11-29 09:25:11 24 4
gpt4 key购买 nike

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 变量?

最佳答案

这是该类(class)的作者 Doug Lea 喜欢使用的极端优化。这是关于 a recent thread 的帖子在关于这个确切主题的 core-libs-dev 邮件列表上,它很好地回答了你的问题。

来自帖子:

...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

关于java - 在ArrayBlockingQueue中,为什么将final成员字段复制到本地final变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2952480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com