将实例字段分配给局部变量 [英] assign instance field to local variable

查看:124
本文介绍了将实例字段分配给局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自JDK的HashMap类的keySet()方法。为什么作者将字段(keySet)分配给局部变量ks?

This is keySet() method on HashMap class from JDK. Why did the author assign the field (keySet) to local variable ks ?

public Set<K> keySet() {
    Set<K> ks;
    return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
}

上面和下面有什么区别?这与线程安全有关吗?

What is the difference between the above and the below ? Does this have something to do with thread-safety ?

public Set<K> keySet() {
    return (keySet == null ? (keySet = new KeySet()) : keySet;
}


推荐答案

为了稍微扩展迈克尔的答案,我希望它能确保 keySet()方法永远不会返回 null ,可能除了提供所提到的性能优势外。

To expand slightly on Michael's answer, I expect it is there to ensure that the keySet() method never returns null, possibly in addition to providing performance benefits noted.

鉴于此代码:

public Set<K> keySet() {
    return (keySet == null ? (keySet = new KeySet()) : keySet;
}

在多线程代码中至少理论上是可行的 keySet 字段可以在第一次读取之间设置为 null keySet == null )和第二次读取,返回它。我没有看过其余的代码,但我认为还有其他地方 keySet 可能被分配 null 。这是否是因为在wil中看到的问题d,或防御措施对作者来说是一个问题。

It would be at least theoretically possible in multi-threaded code that the keySet field could be set to null between the first read (keySet == null) and the second read, where it is returned. I haven't looked at the rest of the code, but I assume there are other places where keySet is potentially assigned null. Whether this is as a result of an issue seen in the wild, or a defensive measure would be a question for the authors.

实际代码:

public Set<K> keySet() {
    Set<K> ks;
    return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
}

...没有此问题,因为该字段仅读取一次。

...doesn't have this problem as the field is only read once.

这篇关于将实例字段分配给局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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