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; 
    } 
dibugger
  • 546
  • 1
  • 7
  • 21
  • 4
    Might be the same reason given in [In ArrayBlockingQueue, why copy final member field into local final variable?](https://stackoverflow.com/questions/2785964/in-arrayblockingqueue-why-copy-final-member-field-into-local-final-variable). – Slaw May 21 '19 at 18:41
  • @Slaw Exactly the same question I believe. Thanks for pointing this out! – dibugger May 21 '19 at 18:45
  • 1
    @GhostCat Not at all! Please do so. Thanks! – dibugger May 21 '19 at 18:46

0 Answers0