Java使用前的变量赋值。为什么? [英] Java Lock variable assignment before use. Why?

查看:190
本文介绍了Java使用前的变量赋值。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在很多Java源代码中(例如 LinkedBlockingDeque )我看到了这样的东西;

In a lot of of the Java source, (for example LinkedBlockingDeque) I see things like this;

final ReentrantLock lock = new ReentrantLock();

public void putLast(E e) throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
       // do stuff
    } finally {
        lock.unlock();
    }
}



我理解基本模式),但我的问题是为什么在使用本地范围的锁定变量之前对其进行赋值:为什么要这样做而不是下面的?

I understand the basic pattern (lock, unlock in finally) but my question is why make an assignment to a locally scoped Lock variable before using it? Why do this instead of the following?

final ReentrantLock lock = new ReentrantLock();

public void putLast(E e) throws InterruptedException {
    this.lock.lock();
    try {
       // do stuff
    } finally {
        lock.unlock();
    }
}

会影响优化吗?第一个例子可以防止锁粗化吗?

Would it affect optimisations? Could the first example prevent lock coarsening?

在注释后编辑:如果你真的不知道为什么,是这种情况。这是从Java源代码,@author标签是Doug Lea所以我很确定它在那里有一个原因。

EDIT after comments: Please don't add an answer if you don't really know why this is the case. This is from the Java source, the @author tag is Doug Lea so I'm pretty sure it's there for a reason. Please don't point out that the code is simply equivalent.

感谢

推荐答案

在方法中赋给局部变量时,编译器可以做一些优化。
请参见在ArrayBlockingQueue中,为什么要复制final member field into local final variable?

When you assign to local variable in method, compiler can do some optimizations. see In ArrayBlockingQueue, why copy final member field into local final variable?

这篇关于Java使用前的变量赋值。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆