Why do HashMap source code use more intermediate variables?

take the keySet () method of HashMap for example:

    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }
Wouldn"t it be more concise to write

in the following form?

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

does the author have any other intentions?


this has something to do with the fact that keySet is modified by volatile.

1 Local variables can prevent shared variables from being accidentally modified.
2 use local variables to reduce the number of reads to volatile variables, and JVM can optimize code execution.

you can refer to this https://stackoverflow.com/que.

.

if you don't consider volatile, it should be to prevent other threads from setting keySet to null, and returning null after the keySet is null.


http://hg.openjdk.java.net/jd.

what age of source code are you looking at? The source code of jdk8 has been changed to the form you wrote.


can be thought of as the author's variable that defines the style nearby. Changing class member variables or method parameters to local variables may seem a little redundant in your small example, but this habit also has several benefits:

1. More concise and clear, local variables can use abbreviations and it is easy to understand, member variables are not advocated to use abbreviations;
2. Can be renamed accurately according to the actual use of the variable;
3. Easy to refactoring, such as extracting into methods, etc.
4. Reduce side effects, such as accidental modification of member variables;
5. It is easier to observe variables when debugging in a single step with a few more lines of code;
6. It is easier to optimize.

personal opinions are for reference only.

Menu