Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

transient volatile Set<K>  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<K> ks)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...