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

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

java - assign instance field to local variable

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

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

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...