Sign in

Why use intermediate variables in HashMap source code?

Innuendo edited in Tue, 17 May 2022

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 simpler 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 intention?

3 Replies
commented on Tue, 17 May 2022

This is related to the fact that keyset is modified by volatile.

Local variables can prevent the shared variables from being modified accidentally. Using local variables can reduce the number of reading volatile variables, and the JVM can optimize the code execution.

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

If volatile is not considered, it should be to prevent other threads from setting keyset to null and returning null after judging keyset null.

commented on Tue, 17 May 2022


What era of source code are you looking at? Jdk8 source code has been changed to the form you write.

commented on Wed, 18 May 2022

It can be regarded as the author's variable definition style. Changing class member variables or method parameters to local variables may seem redundant in your small example, but this habit also has several advantages

1. It is more concise and clear, local variables can use abbreviations, and it is easy to understand, member variables are not advocated to use abbreviations; 2. It can be renamed accurately according to the actual use of variables; 3. It is easy to reconstruct, such as extracting into methods; 4 To reduce side effects, such as modifying member variables; 5. More lines of code, easier to observe variables in single step debugging; 6. Easier to be optimized

Personal opinion, for reference only.

lock This question has been locked and the reply function has been disabled.