assign instance field to local variable

后端 未结 2 1814
小鲜肉
小鲜肉 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:35

    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.

    Given this code:

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

    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.

    The actual code:

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

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

提交回复
热议问题