为什么锁被捕获到局部变量 [英] Why is lock captured to a local variable
本文介绍了为什么锁被捕获到局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
In java JRE I saw the code
private final ReentrantLock lock;
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
为什么锁被捕获到私有变量?我只希望
Why is lock captured to a private variable? I would expect simply
public E poll() {
lock.lock();
推荐答案
主要是为了确保最佳性能.尽管这是真正的微优化,但它可能是对性能敏感的代码,您也可以这样做.
Primarily it is to ensure maximum performance. Although this is a real micro-optimisation, it's probably in performance-sensitive code, and you might as well make it.
您还需要非常小心,确保所使用的锁引用不会发生变化.确保将字段设置为final
,但是采用final
本地引用是本地显式的.
You also need to be very careful that the lock reference you are using doesn't mutate. Sure make the field final
, but taking a final
local reference is locally explicit.
这篇关于为什么锁被捕获到局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文