3

The title might be misleading because I actually don't know if this piece of code is related to concurrency or not, but I guess it is for the sake of thread safe to some extent...

In openJDK 9 -> TreeMap class -> line 121 and line 370. https://zgrepcode.com/java/openjdk/9/java.base/java/util/TreeMap.java Why does the author need to duplicate a comparator inside the getEntryUsingComparator method instead of referring to the class variable comparator itself?

public class TreeMap<K,V> 
    extends AbstractMap<K,V> 
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable 
{ 

    private final Comparator<? super K> comparator; 

    // other code
    final Entry<K,V> getEntryUsingComparator(Object key) { 
    @SuppressWarnings("unchecked") 
        K k = (K) key; 
        Comparator<? super K> cpr = comparator;  // why duplicate a comparator here? 
        if (cpr != null) { 
            Entry<K,V> p = root; 
            while (p != null) { 
                int cmp = cpr.compare(k, p.key); 
                if (cmp < 0) 
                    p = p.left; 
                else if (cmp > 0) 
                    p = p.right; 
                else 
                    return p; 
            } 
        } 
        return null; 
    } 
3

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.