assign instance field to local variable

后端 未结 2 1813
小鲜肉
小鲜肉 2020-12-15 21:58

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

2条回答
  •  情深已故
    2020-12-15 22:41

    If you look at the keySet declaration in the abstract class AbstractMap, you will see that it is defined as:

    transient volatile Set  keySet;
    

    Since it is volatile, reading it just once by using the local variable assignment is cheaper than reading it twice as would be in the other example you provided.

    Furthermore, if you were to return the keySet variable directly, then all the client code would be dealing with a volatile reference vs. a non-volatile reference (i.e. the Set ks)

提交回复
热议问题