1 /*
   2  * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 
  28 import java.lang.ref.WeakReference;
  29 import java.lang.ref.ReferenceQueue;
  30 import java.util.concurrent.ThreadLocalRandom;
  31 import java.util.function.Consumer;
  32 
  33 
  34 /**
  35  * Hash table based implementation of the <tt>Map</tt> interface, with
  36  * <em>weak keys</em>.
  37  * An entry in a <tt>WeakHashMap</tt> will automatically be removed when
  38  * its key is no longer in ordinary use.  More precisely, the presence of a
  39  * mapping for a given key will not prevent the key from being discarded by the
  40  * garbage collector, that is, made finalizable, finalized, and then reclaimed.
  41  * When a key has been discarded its entry is effectively removed from the map,
  42  * so this class behaves somewhat differently from other <tt>Map</tt>
  43  * implementations.
  44  *
  45  * <p> Both null values and the null key are supported. This class has
  46  * performance characteristics similar to those of the <tt>HashMap</tt>
  47  * class, and has the same efficiency parameters of <em>initial capacity</em>
  48  * and <em>load factor</em>.
  49  *
  50  * <p> Like most collection classes, this class is not synchronized.
  51  * A synchronized <tt>WeakHashMap</tt> may be constructed using the
  52  * {@link Collections#synchronizedMap Collections.synchronizedMap}
  53  * method.
  54  *
  55  * <p> This class is intended primarily for use with key objects whose
  56  * <tt>equals</tt> methods test for object identity using the
  57  * <tt>==</tt> operator.  Once such a key is discarded it can never be
  58  * recreated, so it is impossible to do a lookup of that key in a
  59  * <tt>WeakHashMap</tt> at some later time and be surprised that its entry
  60  * has been removed.  This class will work perfectly well with key objects
  61  * whose <tt>equals</tt> methods are not based upon object identity, such
  62  * as <tt>String</tt> instances.  With such recreatable key objects,
  63  * however, the automatic removal of <tt>WeakHashMap</tt> entries whose
  64  * keys have been discarded may prove to be confusing.
  65  *
  66  * <p> The behavior of the <tt>WeakHashMap</tt> class depends in part upon
  67  * the actions of the garbage collector, so several familiar (though not
  68  * required) <tt>Map</tt> invariants do not hold for this class.  Because
  69  * the garbage collector may discard keys at any time, a
  70  * <tt>WeakHashMap</tt> may behave as though an unknown thread is silently
  71  * removing entries.  In particular, even if you synchronize on a
  72  * <tt>WeakHashMap</tt> instance and invoke none of its mutator methods, it
  73  * is possible for the <tt>size</tt> method to return smaller values over
  74  * time, for the <tt>isEmpty</tt> method to return <tt>false</tt> and
  75  * then <tt>true</tt>, for the <tt>containsKey</tt> method to return
  76  * <tt>true</tt> and later <tt>false</tt> for a given key, for the
  77  * <tt>get</tt> method to return a value for a given key but later return
  78  * <tt>null</tt>, for the <tt>put</tt> method to return
  79  * <tt>null</tt> and the <tt>remove</tt> method to return
  80  * <tt>false</tt> for a key that previously appeared to be in the map, and
  81  * for successive examinations of the key set, the value collection, and
  82  * the entry set to yield successively smaller numbers of elements.
  83  *
  84  * <p> Each key object in a <tt>WeakHashMap</tt> is stored indirectly as
  85  * the referent of a weak reference.  Therefore a key will automatically be
  86  * removed only after the weak references to it, both inside and outside of the
  87  * map, have been cleared by the garbage collector.
  88  *
  89  * <p> <strong>Implementation note:</strong> The value objects in a
  90  * <tt>WeakHashMap</tt> are held by ordinary strong references.  Thus care
  91  * should be taken to ensure that value objects do not strongly refer to their
  92  * own keys, either directly or indirectly, since that will prevent the keys
  93  * from being discarded.  Note that a value object may refer indirectly to its
  94  * key via the <tt>WeakHashMap</tt> itself; that is, a value object may
  95  * strongly refer to some other key object whose associated value object, in
  96  * turn, strongly refers to the key of the first value object.  If the values
  97  * in the map do not rely on the map holding strong references to them, one way
  98  * to deal with this is to wrap values themselves within
  99  * <tt>WeakReferences</tt> before
 100  * inserting, as in: <tt>m.put(key, new WeakReference(value))</tt>,
 101  * and then unwrapping upon each <tt>get</tt>.
 102  *
 103  * <p>The iterators returned by the <tt>iterator</tt> method of the collections
 104  * returned by all of this class's "collection view methods" are
 105  * <i>fail-fast</i>: if the map is structurally modified at any time after the
 106  * iterator is created, in any way except through the iterator's own
 107  * <tt>remove</tt> method, the iterator will throw a {@link
 108  * ConcurrentModificationException}.  Thus, in the face of concurrent
 109  * modification, the iterator fails quickly and cleanly, rather than risking
 110  * arbitrary, non-deterministic behavior at an undetermined time in the future.
 111  *
 112  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
 113  * as it is, generally speaking, impossible to make any hard guarantees in the
 114  * presence of unsynchronized concurrent modification.  Fail-fast iterators
 115  * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
 116  * Therefore, it would be wrong to write a program that depended on this
 117  * exception for its correctness:  <i>the fail-fast behavior of iterators
 118  * should be used only to detect bugs.</i>
 119  *
 120  * <p>This class is a member of the
 121  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 122  * Java Collections Framework</a>.
 123  *
 124  * @param <K> the type of keys maintained by this map
 125  * @param <V> the type of mapped values
 126  *
 127  * @author      Doug Lea
 128  * @author      Josh Bloch
 129  * @author      Mark Reinhold
 130  * @since       1.2
 131  * @see         java.util.HashMap
 132  * @see         java.lang.ref.WeakReference
 133  */
 134 public class WeakHashMap<K,V>
 135     extends AbstractMap<K,V>
 136     implements Map<K,V> {
 137 
 138     /**
 139      * The default initial capacity -- MUST be a power of two.
 140      */
 141     private static final int DEFAULT_INITIAL_CAPACITY = 16;
 142 
 143     /**
 144      * The maximum capacity, used if a higher value is implicitly specified
 145      * by either of the constructors with arguments.
 146      * MUST be a power of two <= 1<<30.
 147      */
 148     private static final int MAXIMUM_CAPACITY = 1 << 30;
 149 
 150     /**
 151      * The load factor used when none specified in constructor.
 152      */
 153     private static final float DEFAULT_LOAD_FACTOR = 0.75f;
 154 
 155     /**
 156      * The table, resized as necessary. Length MUST Always be a power of two.
 157      */
 158     Entry<K,V>[] table;
 159 
 160     /**
 161      * The number of key-value mappings contained in this weak hash map.
 162      */
 163     private int size;
 164 
 165     /**
 166      * The next size value at which to resize (capacity * load factor).
 167      */
 168     private int threshold;
 169 
 170     /**
 171      * The load factor for the hash table.
 172      */
 173     private final float loadFactor;
 174 
 175     /**
 176      * Reference queue for cleared WeakEntries
 177      */
 178     private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
 179 
 180     /**
 181      * The number of times this WeakHashMap has been structurally modified.
 182      * Structural modifications are those that change the number of
 183      * mappings in the map or otherwise modify its internal structure
 184      * (e.g., rehash).  This field is used to make iterators on
 185      * Collection-views of the map fail-fast.
 186      *
 187      * @see ConcurrentModificationException
 188      */
 189     int modCount;
 190 
 191     private static class Holder {
 192         static final boolean USE_HASHSEED;
 193 
 194         static {
 195             String hashSeedProp = java.security.AccessController.doPrivileged(
 196                     new sun.security.action.GetPropertyAction(
 197                         "jdk.map.useRandomSeed"));
 198             boolean localBool = (null != hashSeedProp)
 199                     ? Boolean.parseBoolean(hashSeedProp) : false;
 200             USE_HASHSEED = localBool;
 201         }
 202     }
 203 
 204     /**
 205      * A randomizing value associated with this instance that is applied to
 206      * hash code of keys to make hash collisions harder to find.
 207      *
 208      * Non-final so it can be set lazily, but be sure not to set more than once.
 209      */
 210     transient int hashSeed;
 211 
 212     /**
 213      * Initialize the hashing mask value.
 214      */
 215     final void initHashSeed() {
 216         if (sun.misc.VM.isBooted() && Holder.USE_HASHSEED) {
 217             // Do not set hashSeed more than once!
 218             // assert hashSeed == 0;
 219             int seed = ThreadLocalRandom.current().nextInt();
 220             hashSeed = (seed != 0) ? seed : 1;
 221         }
 222     }
 223 
 224     @SuppressWarnings("unchecked")
 225     private Entry<K,V>[] newTable(int n) {
 226         return (Entry<K,V>[]) new Entry<?,?>[n];
 227     }
 228 
 229     /**
 230      * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial
 231      * capacity and the given load factor.
 232      *
 233      * @param  initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
 234      * @param  loadFactor      The load factor of the <tt>WeakHashMap</tt>
 235      * @throws IllegalArgumentException if the initial capacity is negative,
 236      *         or if the load factor is nonpositive.
 237      */
 238     public WeakHashMap(int initialCapacity, float loadFactor) {
 239         if (initialCapacity < 0)
 240             throw new IllegalArgumentException("Illegal Initial Capacity: "+
 241                                                initialCapacity);
 242         if (initialCapacity > MAXIMUM_CAPACITY)
 243             initialCapacity = MAXIMUM_CAPACITY;
 244 
 245         if (loadFactor <= 0 || Float.isNaN(loadFactor))
 246             throw new IllegalArgumentException("Illegal Load factor: "+
 247                                                loadFactor);
 248         int capacity = 1;
 249         while (capacity < initialCapacity)
 250             capacity <<= 1;
 251         table = newTable(capacity);
 252         this.loadFactor = loadFactor;
 253         threshold = (int)(capacity * loadFactor);
 254         initHashSeed();
 255     }
 256 
 257     /**
 258      * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial
 259      * capacity and the default load factor (0.75).
 260      *
 261      * @param  initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
 262      * @throws IllegalArgumentException if the initial capacity is negative
 263      */
 264     public WeakHashMap(int initialCapacity) {
 265         this(initialCapacity, DEFAULT_LOAD_FACTOR);
 266     }
 267 
 268     /**
 269      * Constructs a new, empty <tt>WeakHashMap</tt> with the default initial
 270      * capacity (16) and load factor (0.75).
 271      */
 272     public WeakHashMap() {
 273         this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
 274     }
 275 
 276     /**
 277      * Constructs a new <tt>WeakHashMap</tt> with the same mappings as the
 278      * specified map.  The <tt>WeakHashMap</tt> is created with the default
 279      * load factor (0.75) and an initial capacity sufficient to hold the
 280      * mappings in the specified map.
 281      *
 282      * @param   m the map whose mappings are to be placed in this map
 283      * @throws  NullPointerException if the specified map is null
 284      * @since   1.3
 285      */
 286     public WeakHashMap(Map<? extends K, ? extends V> m) {
 287         this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
 288                 DEFAULT_INITIAL_CAPACITY),
 289              DEFAULT_LOAD_FACTOR);
 290         putAll(m);
 291     }
 292 
 293     // internal utilities
 294 
 295     /**
 296      * Value representing null keys inside tables.
 297      */
 298     private static final Object NULL_KEY = new Object();
 299 
 300     /**
 301      * Use NULL_KEY for key if it is null.
 302      */
 303     private static Object maskNull(Object key) {
 304         return (key == null) ? NULL_KEY : key;
 305     }
 306 
 307     /**
 308      * Returns internal representation of null key back to caller as null.
 309      */
 310     static Object unmaskNull(Object key) {
 311         return (key == NULL_KEY) ? null : key;
 312     }
 313 
 314     /**
 315      * Checks for equality of non-null reference x and possibly-null y.  By
 316      * default uses Object.equals.
 317      */
 318     private static boolean eq(Object x, Object y) {
 319         return x == y || x.equals(y);
 320     }
 321 
 322     /**
 323      * Retrieve object hash code and applies a supplemental hash function to the
 324      * result hash, which defends against poor quality hash functions.  This is
 325      * critical because HashMap uses power-of-two length hash tables, that
 326      * otherwise encounter collisions for hashCodes that do not differ
 327      * in lower bits.
 328      */
 329     final int hash(Object k) {
 330         int h = hashSeed ^ k.hashCode();
 331 
 332         // This function ensures that hashCodes that differ only by
 333         // constant multiples at each bit position have a bounded
 334         // number of collisions (approximately 8 at default load factor).
 335         h ^= (h >>> 20) ^ (h >>> 12);
 336         return h ^ (h >>> 7) ^ (h >>> 4);
 337     }
 338 
 339     /**
 340      * Returns index for hash code h.
 341      */
 342     private static int indexFor(int h, int length) {
 343         return h & (length-1);
 344     }
 345 
 346     /**
 347      * Expunges stale entries from the table.
 348      */
 349     private void expungeStaleEntries() {
 350         for (Object x; (x = queue.poll()) != null; ) {
 351             synchronized (queue) {
 352                 @SuppressWarnings("unchecked")
 353                     Entry<K,V> e = (Entry<K,V>) x;
 354                 int i = indexFor(e.hash, table.length);
 355 
 356                 Entry<K,V> prev = table[i];
 357                 Entry<K,V> p = prev;
 358                 while (p != null) {
 359                     Entry<K,V> next = p.next;
 360                     if (p == e) {
 361                         if (prev == e)
 362                             table[i] = next;
 363                         else
 364                             prev.next = next;
 365                         // Must not null out e.next;
 366                         // stale entries may be in use by a HashIterator
 367                         e.value = null; // Help GC
 368                         size--;
 369                         break;
 370                     }
 371                     prev = p;
 372                     p = next;
 373                 }
 374             }
 375         }
 376     }
 377 
 378     /**
 379      * Returns the table after first expunging stale entries.
 380      */
 381     private Entry<K,V>[] getTable() {
 382         expungeStaleEntries();
 383         return table;
 384     }
 385 
 386     /**
 387      * Returns the number of key-value mappings in this map.
 388      * This result is a snapshot, and may not reflect unprocessed
 389      * entries that will be removed before next attempted access
 390      * because they are no longer referenced.
 391      */
 392     public int size() {
 393         if (size == 0)
 394             return 0;
 395         expungeStaleEntries();
 396         return size;
 397     }
 398 
 399     /**
 400      * Returns <tt>true</tt> if this map contains no key-value mappings.
 401      * This result is a snapshot, and may not reflect unprocessed
 402      * entries that will be removed before next attempted access
 403      * because they are no longer referenced.
 404      */
 405     public boolean isEmpty() {
 406         return size() == 0;
 407     }
 408 
 409     /**
 410      * Returns the value to which the specified key is mapped,
 411      * or {@code null} if this map contains no mapping for the key.
 412      *
 413      * <p>More formally, if this map contains a mapping from a key
 414      * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
 415      * key.equals(k))}, then this method returns {@code v}; otherwise
 416      * it returns {@code null}.  (There can be at most one such mapping.)
 417      *
 418      * <p>A return value of {@code null} does not <i>necessarily</i>
 419      * indicate that the map contains no mapping for the key; it's also
 420      * possible that the map explicitly maps the key to {@code null}.
 421      * The {@link #containsKey containsKey} operation may be used to
 422      * distinguish these two cases.
 423      *
 424      * @see #put(Object, Object)
 425      */
 426     public V get(Object key) {
 427         Object k = maskNull(key);
 428         int h = hash(k);
 429         Entry<K,V>[] tab = getTable();
 430         int index = indexFor(h, tab.length);
 431         Entry<K,V> e = tab[index];
 432         while (e != null) {
 433             if (e.hash == h && eq(k, e.get()))
 434                 return e.value;
 435             e = e.next;
 436         }
 437         return null;
 438     }
 439 
 440     /**
 441      * Returns <tt>true</tt> if this map contains a mapping for the
 442      * specified key.
 443      *
 444      * @param  key   The key whose presence in this map is to be tested
 445      * @return <tt>true</tt> if there is a mapping for <tt>key</tt>;
 446      *         <tt>false</tt> otherwise
 447      */
 448     public boolean containsKey(Object key) {
 449         return getEntry(key) != null;
 450     }
 451 
 452     /**
 453      * Returns the entry associated with the specified key in this map.
 454      * Returns null if the map contains no mapping for this key.
 455      */
 456     Entry<K,V> getEntry(Object key) {
 457         Object k = maskNull(key);
 458         int h = hash(k);
 459         Entry<K,V>[] tab = getTable();
 460         int index = indexFor(h, tab.length);
 461         Entry<K,V> e = tab[index];
 462         while (e != null && !(e.hash == h && eq(k, e.get())))
 463             e = e.next;
 464         return e;
 465     }
 466 
 467     /**
 468      * Associates the specified value with the specified key in this map.
 469      * If the map previously contained a mapping for this key, the old
 470      * value is replaced.
 471      *
 472      * @param key key with which the specified value is to be associated.
 473      * @param value value to be associated with the specified key.
 474      * @return the previous value associated with <tt>key</tt>, or
 475      *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 476      *         (A <tt>null</tt> return can also indicate that the map
 477      *         previously associated <tt>null</tt> with <tt>key</tt>.)
 478      */
 479     public V put(K key, V value) {
 480         Object k = maskNull(key);
 481         int h = hash(k);
 482         Entry<K,V>[] tab = getTable();
 483         int i = indexFor(h, tab.length);
 484 
 485         for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
 486             if (h == e.hash && eq(k, e.get())) {
 487                 V oldValue = e.value;
 488                 if (value != oldValue)
 489                     e.value = value;
 490                 return oldValue;
 491             }
 492         }
 493 
 494         modCount++;
 495         Entry<K,V> e = tab[i];
 496         tab[i] = new Entry<>(k, value, queue, h, e);
 497         if (++size >= threshold)
 498             resize(tab.length * 2);
 499         return null;
 500     }
 501 
 502     /**
 503      * Rehashes the contents of this map into a new array with a
 504      * larger capacity.  This method is called automatically when the
 505      * number of keys in this map reaches its threshold.
 506      *
 507      * If current capacity is MAXIMUM_CAPACITY, this method does not
 508      * resize the map, but sets threshold to Integer.MAX_VALUE.
 509      * This has the effect of preventing future calls.
 510      *
 511      * @param newCapacity the new capacity, MUST be a power of two;
 512      *        must be greater than current capacity unless current
 513      *        capacity is MAXIMUM_CAPACITY (in which case value
 514      *        is irrelevant).
 515      */
 516     void resize(int newCapacity) {
 517         Entry<K,V>[] oldTable = getTable();
 518         int oldCapacity = oldTable.length;
 519         if (oldCapacity == MAXIMUM_CAPACITY) {
 520             threshold = Integer.MAX_VALUE;
 521             return;
 522         }
 523 
 524         Entry<K,V>[] newTable = newTable(newCapacity);
 525         transfer(oldTable, newTable);
 526         table = newTable;
 527 
 528         /*
 529          * If ignoring null elements and processing ref queue caused massive
 530          * shrinkage, then restore old table.  This should be rare, but avoids
 531          * unbounded expansion of garbage-filled tables.
 532          */
 533         if (size >= threshold / 2) {
 534             threshold = (int)(newCapacity * loadFactor);
 535         } else {
 536             expungeStaleEntries();
 537             transfer(newTable, oldTable);
 538             table = oldTable;
 539         }
 540     }
 541 
 542     /** Transfers all entries from src to dest tables */
 543     private void transfer(Entry<K,V>[] src, Entry<K,V>[] dest) {
 544         for (int j = 0; j < src.length; ++j) {
 545             Entry<K,V> e = src[j];
 546             src[j] = null;
 547             while (e != null) {
 548                 Entry<K,V> next = e.next;
 549                 Object key = e.get();
 550                 if (key == null) {
 551                     e.next = null;  // Help GC
 552                     e.value = null; //  "   "
 553                     size--;
 554                 } else {
 555                     int i = indexFor(e.hash, dest.length);
 556                     e.next = dest[i];
 557                     dest[i] = e;
 558                 }
 559                 e = next;
 560             }
 561         }
 562     }
 563 
 564     /**
 565      * Copies all of the mappings from the specified map to this map.
 566      * These mappings will replace any mappings that this map had for any
 567      * of the keys currently in the specified map.
 568      *
 569      * @param m mappings to be stored in this map.
 570      * @throws  NullPointerException if the specified map is null.
 571      */
 572     public void putAll(Map<? extends K, ? extends V> m) {
 573         int numKeysToBeAdded = m.size();
 574         if (numKeysToBeAdded == 0)
 575             return;
 576 
 577         /*
 578          * Expand the map if the map if the number of mappings to be added
 579          * is greater than or equal to threshold.  This is conservative; the
 580          * obvious condition is (m.size() + size) >= threshold, but this
 581          * condition could result in a map with twice the appropriate capacity,
 582          * if the keys to be added overlap with the keys already in this map.
 583          * By using the conservative calculation, we subject ourself
 584          * to at most one extra resize.
 585          */
 586         if (numKeysToBeAdded > threshold) {
 587             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
 588             if (targetCapacity > MAXIMUM_CAPACITY)
 589                 targetCapacity = MAXIMUM_CAPACITY;
 590             int newCapacity = table.length;
 591             while (newCapacity < targetCapacity)
 592                 newCapacity <<= 1;
 593             if (newCapacity > table.length)
 594                 resize(newCapacity);
 595         }
 596 
 597         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
 598             put(e.getKey(), e.getValue());
 599     }
 600 
 601     /**
 602      * Removes the mapping for a key from this weak hash map if it is present.
 603      * More formally, if this map contains a mapping from key <tt>k</tt> to
 604      * value <tt>v</tt> such that <code>(key==null ?  k==null :
 605      * key.equals(k))</code>, that mapping is removed.  (The map can contain
 606      * at most one such mapping.)
 607      *
 608      * <p>Returns the value to which this map previously associated the key,
 609      * or <tt>null</tt> if the map contained no mapping for the key.  A
 610      * return value of <tt>null</tt> does not <i>necessarily</i> indicate
 611      * that the map contained no mapping for the key; it's also possible
 612      * that the map explicitly mapped the key to <tt>null</tt>.
 613      *
 614      * <p>The map will not contain a mapping for the specified key once the
 615      * call returns.
 616      *
 617      * @param key key whose mapping is to be removed from the map
 618      * @return the previous value associated with <tt>key</tt>, or
 619      *         <tt>null</tt> if there was no mapping for <tt>key</tt>
 620      */
 621     public V remove(Object key) {
 622         Object k = maskNull(key);
 623         int h = hash(k);
 624         Entry<K,V>[] tab = getTable();
 625         int i = indexFor(h, tab.length);
 626         Entry<K,V> prev = tab[i];
 627         Entry<K,V> e = prev;
 628 
 629         while (e != null) {
 630             Entry<K,V> next = e.next;
 631             if (h == e.hash && eq(k, e.get())) {
 632                 modCount++;
 633                 size--;
 634                 if (prev == e)
 635                     tab[i] = next;
 636                 else
 637                     prev.next = next;
 638                 return e.value;
 639             }
 640             prev = e;
 641             e = next;
 642         }
 643 
 644         return null;
 645     }
 646 
 647     /** Special version of remove needed by Entry set */
 648     boolean removeMapping(Object o) {
 649         if (!(o instanceof Map.Entry))
 650             return false;
 651         Entry<K,V>[] tab = getTable();
 652         Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
 653         Object k = maskNull(entry.getKey());
 654         int h = hash(k);
 655         int i = indexFor(h, tab.length);
 656         Entry<K,V> prev = tab[i];
 657         Entry<K,V> e = prev;
 658 
 659         while (e != null) {
 660             Entry<K,V> next = e.next;
 661             if (h == e.hash && e.equals(entry)) {
 662                 modCount++;
 663                 size--;
 664                 if (prev == e)
 665                     tab[i] = next;
 666                 else
 667                     prev.next = next;
 668                 return true;
 669             }
 670             prev = e;
 671             e = next;
 672         }
 673 
 674         return false;
 675     }
 676 
 677     /**
 678      * Removes all of the mappings from this map.
 679      * The map will be empty after this call returns.
 680      */
 681     public void clear() {
 682         // clear out ref queue. We don't need to expunge entries
 683         // since table is getting cleared.
 684         while (queue.poll() != null)
 685             ;
 686 
 687         modCount++;
 688         Arrays.fill(table, null);
 689         size = 0;
 690 
 691         // Allocation of array may have caused GC, which may have caused
 692         // additional entries to go stale.  Removing these entries from the
 693         // reference queue will make them eligible for reclamation.
 694         while (queue.poll() != null)
 695             ;
 696     }
 697 
 698     /**
 699      * Returns <tt>true</tt> if this map maps one or more keys to the
 700      * specified value.
 701      *
 702      * @param value value whose presence in this map is to be tested
 703      * @return <tt>true</tt> if this map maps one or more keys to the
 704      *         specified value
 705      */
 706     public boolean containsValue(Object value) {
 707         if (value==null)
 708             return containsNullValue();
 709 
 710         Entry<K,V>[] tab = getTable();
 711         for (int i = tab.length; i-- > 0;)
 712             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
 713                 if (value.equals(e.value))
 714                     return true;
 715         return false;
 716     }
 717 
 718     /**
 719      * Special-case code for containsValue with null argument
 720      */
 721     private boolean containsNullValue() {
 722         Entry<K,V>[] tab = getTable();
 723         for (int i = tab.length; i-- > 0;)
 724             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
 725                 if (e.value==null)
 726                     return true;
 727         return false;
 728     }
 729 
 730     /**
 731      * The entries in this hash table extend WeakReference, using its main ref
 732      * field as the key.
 733      */
 734     private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
 735         V value;
 736         final int hash;
 737         Entry<K,V> next;
 738 
 739         /**
 740          * Creates new entry.
 741          */
 742         Entry(Object key, V value,
 743               ReferenceQueue<Object> queue,
 744               int hash, Entry<K,V> next) {
 745             super(key, queue);
 746             this.value = value;
 747             this.hash  = hash;
 748             this.next  = next;
 749         }
 750 
 751         @SuppressWarnings("unchecked")
 752         public K getKey() {
 753             return (K) WeakHashMap.unmaskNull(get());
 754         }
 755 
 756         public V getValue() {
 757             return value;
 758         }
 759 
 760         public V setValue(V newValue) {
 761             V oldValue = value;
 762             value = newValue;
 763             return oldValue;
 764         }
 765 
 766         public boolean equals(Object o) {
 767             if (!(o instanceof Map.Entry))
 768                 return false;
 769             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
 770             K k1 = getKey();
 771             Object k2 = e.getKey();
 772             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
 773                 V v1 = getValue();
 774                 Object v2 = e.getValue();
 775                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
 776                     return true;
 777             }
 778             return false;
 779         }
 780 
 781         public int hashCode() {
 782             K k = getKey();
 783             V v = getValue();
 784             return ((k==null ? 0 : k.hashCode()) ^
 785                     (v==null ? 0 : v.hashCode()));
 786         }
 787 
 788         public String toString() {
 789             return getKey() + "=" + getValue();
 790         }
 791     }
 792 
 793     private abstract class HashIterator<T> implements Iterator<T> {
 794         private int index;
 795         private Entry<K,V> entry = null;
 796         private Entry<K,V> lastReturned = null;
 797         private int expectedModCount = modCount;
 798 
 799         /**
 800          * Strong reference needed to avoid disappearance of key
 801          * between hasNext and next
 802          */
 803         private Object nextKey = null;
 804 
 805         /**
 806          * Strong reference needed to avoid disappearance of key
 807          * between nextEntry() and any use of the entry
 808          */
 809         private Object currentKey = null;
 810 
 811         HashIterator() {
 812             index = isEmpty() ? 0 : table.length;
 813         }
 814 
 815         public boolean hasNext() {
 816             Entry<K,V>[] t = table;
 817 
 818             while (nextKey == null) {
 819                 Entry<K,V> e = entry;
 820                 int i = index;
 821                 while (e == null && i > 0)
 822                     e = t[--i];
 823                 entry = e;
 824                 index = i;
 825                 if (e == null) {
 826                     currentKey = null;
 827                     return false;
 828                 }
 829                 nextKey = e.get(); // hold on to key in strong ref
 830                 if (nextKey == null)
 831                     entry = entry.next;
 832             }
 833             return true;
 834         }
 835 
 836         /** The common parts of next() across different types of iterators */
 837         protected Entry<K,V> nextEntry() {
 838             if (modCount != expectedModCount)
 839                 throw new ConcurrentModificationException();
 840             if (nextKey == null && !hasNext())
 841                 throw new NoSuchElementException();
 842 
 843             lastReturned = entry;
 844             entry = entry.next;
 845             currentKey = nextKey;
 846             nextKey = null;
 847             return lastReturned;
 848         }
 849 
 850         public void remove() {
 851             if (lastReturned == null)
 852                 throw new IllegalStateException();
 853             if (modCount != expectedModCount)
 854                 throw new ConcurrentModificationException();
 855 
 856             WeakHashMap.this.remove(currentKey);
 857             expectedModCount = modCount;
 858             lastReturned = null;
 859             currentKey = null;
 860         }
 861 
 862     }
 863 
 864     private class ValueIterator extends HashIterator<V> {
 865         public V next() {
 866             return nextEntry().value;
 867         }
 868     }
 869 
 870     private class KeyIterator extends HashIterator<K> {
 871         public K next() {
 872             return nextEntry().getKey();
 873         }
 874     }
 875 
 876     private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
 877         public Map.Entry<K,V> next() {
 878             return nextEntry();
 879         }
 880     }
 881 
 882     // Views
 883 
 884     private transient Set<Map.Entry<K,V>> entrySet = null;
 885 
 886     /**
 887      * Returns a {@link Set} view of the keys contained in this map.
 888      * The set is backed by the map, so changes to the map are
 889      * reflected in the set, and vice-versa.  If the map is modified
 890      * while an iteration over the set is in progress (except through
 891      * the iterator's own <tt>remove</tt> operation), the results of
 892      * the iteration are undefined.  The set supports element removal,
 893      * which removes the corresponding mapping from the map, via the
 894      * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
 895      * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
 896      * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
 897      * operations.
 898      */
 899     public Set<K> keySet() {
 900         Set<K> ks = keySet;
 901         return (ks != null ? ks : (keySet = new KeySet()));
 902     }
 903 
 904     private class KeySet extends AbstractSet<K> {
 905         public Iterator<K> iterator() {
 906             return new KeyIterator();
 907         }
 908 
 909         public int size() {
 910             return WeakHashMap.this.size();
 911         }
 912 
 913         public boolean contains(Object o) {
 914             return containsKey(o);
 915         }
 916 
 917         public boolean remove(Object o) {
 918             if (containsKey(o)) {
 919                 WeakHashMap.this.remove(o);
 920                 return true;
 921             }
 922             else
 923                 return false;
 924         }
 925 
 926         public void clear() {
 927             WeakHashMap.this.clear();
 928         }
 929 
 930         public Spliterator<K> spliterator() {
 931             return new KeySpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
 932         }
 933     }
 934 
 935     /**
 936      * Returns a {@link Collection} view of the values contained in this map.
 937      * The collection is backed by the map, so changes to the map are
 938      * reflected in the collection, and vice-versa.  If the map is
 939      * modified while an iteration over the collection is in progress
 940      * (except through the iterator's own <tt>remove</tt> operation),
 941      * the results of the iteration are undefined.  The collection
 942      * supports element removal, which removes the corresponding
 943      * mapping from the map, via the <tt>Iterator.remove</tt>,
 944      * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
 945      * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
 946      * support the <tt>add</tt> or <tt>addAll</tt> operations.
 947      */
 948     public Collection<V> values() {
 949         Collection<V> vs = values;
 950         return (vs != null) ? vs : (values = new Values());
 951     }
 952 
 953     private class Values extends AbstractCollection<V> {
 954         public Iterator<V> iterator() {
 955             return new ValueIterator();
 956         }
 957 
 958         public int size() {
 959             return WeakHashMap.this.size();
 960         }
 961 
 962         public boolean contains(Object o) {
 963             return containsValue(o);
 964         }
 965 
 966         public void clear() {
 967             WeakHashMap.this.clear();
 968         }
 969 
 970         public Spliterator<V> spliterator() {
 971             return new ValueSpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
 972         }
 973     }
 974 
 975     /**
 976      * Returns a {@link Set} view of the mappings contained in this map.
 977      * The set is backed by the map, so changes to the map are
 978      * reflected in the set, and vice-versa.  If the map is modified
 979      * while an iteration over the set is in progress (except through
 980      * the iterator's own <tt>remove</tt> operation, or through the
 981      * <tt>setValue</tt> operation on a map entry returned by the
 982      * iterator) the results of the iteration are undefined.  The set
 983      * supports element removal, which removes the corresponding
 984      * mapping from the map, via the <tt>Iterator.remove</tt>,
 985      * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
 986      * <tt>clear</tt> operations.  It does not support the
 987      * <tt>add</tt> or <tt>addAll</tt> operations.
 988      */
 989     public Set<Map.Entry<K,V>> entrySet() {
 990         Set<Map.Entry<K,V>> es = entrySet;
 991         return es != null ? es : (entrySet = new EntrySet());
 992     }
 993 
 994     private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
 995         public Iterator<Map.Entry<K,V>> iterator() {
 996             return new EntryIterator();
 997         }
 998 
 999         public boolean contains(Object o) {
1000             if (!(o instanceof Map.Entry))
1001                 return false;
1002             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1003             Entry<K,V> candidate = getEntry(e.getKey());
1004             return candidate != null && candidate.equals(e);
1005         }
1006 
1007         public boolean remove(Object o) {
1008             return removeMapping(o);
1009         }
1010 
1011         public int size() {
1012             return WeakHashMap.this.size();
1013         }
1014 
1015         public void clear() {
1016             WeakHashMap.this.clear();
1017         }
1018 
1019         private List<Map.Entry<K,V>> deepCopy() {
1020             List<Map.Entry<K,V>> list = new ArrayList<>(size());
1021             for (Map.Entry<K,V> e : this)
1022                 list.add(new AbstractMap.SimpleEntry<>(e));
1023             return list;
1024         }
1025 
1026         public Object[] toArray() {
1027             return deepCopy().toArray();
1028         }
1029 
1030         public <T> T[] toArray(T[] a) {
1031             return deepCopy().toArray(a);
1032         }
1033 
1034         public Spliterator<Map.Entry<K,V>> spliterator() {
1035             return new EntrySpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
1036         }
1037     }
1038 
1039     /**
1040      * Similar form as other hash Spliterators, but skips dead
1041      * elements.
1042      */
1043     static class WeakHashMapSpliterator<K,V> {
1044         final WeakHashMap<K,V> map;
1045         WeakHashMap.Entry<K,V> current; // current node
1046         int index;             // current index, modified on advance/split
1047         int fence;             // -1 until first use; then one past last index
1048         int est;               // size estimate
1049         int expectedModCount;  // for comodification checks
1050 
1051         WeakHashMapSpliterator(WeakHashMap<K,V> m, int origin,
1052                                int fence, int est,
1053                                int expectedModCount) {
1054             this.map = m;
1055             this.index = origin;
1056             this.fence = fence;
1057             this.est = est;
1058             this.expectedModCount = expectedModCount;
1059         }
1060 
1061         final int getFence() { // initialize fence and size on first use
1062             int hi;
1063             if ((hi = fence) < 0) {
1064                 WeakHashMap<K,V> m = map;
1065                 est = m.size();
1066                 expectedModCount = m.modCount;
1067                 hi = fence = m.table.length;
1068             }
1069             return hi;
1070         }
1071 
1072         public final long estimateSize() {
1073             getFence(); // force init
1074             return (long) est;
1075         }
1076     }
1077 
1078     static final class KeySpliterator<K,V>
1079         extends WeakHashMapSpliterator<K,V>
1080         implements Spliterator<K> {
1081         KeySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1082                        int expectedModCount) {
1083             super(m, origin, fence, est, expectedModCount);
1084         }
1085 
1086         public KeySpliterator<K,V> trySplit() {
1087             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1088             return (lo >= mid) ? null :
1089                 new KeySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
1090                                         expectedModCount);
1091         }
1092 
1093         public void forEachRemaining(Consumer<? super K> action) {
1094             int i, hi, mc;
1095             if (action == null)
1096                 throw new NullPointerException();
1097             WeakHashMap<K,V> m = map;
1098             WeakHashMap.Entry<K,V>[] tab = m.table;
1099             if ((hi = fence) < 0) {
1100                 mc = expectedModCount = m.modCount;
1101                 hi = fence = tab.length;
1102             }
1103             else
1104                 mc = expectedModCount;
1105             if (tab.length >= hi && (i = index) >= 0 &&
1106                 (i < (index = hi) || current != null)) {
1107                 WeakHashMap.Entry<K,V> p = current;
1108                 current = null; // exhaust
1109                 do {
1110                     if (p == null)
1111                         p = tab[i++];
1112                     else {
1113                         Object x = p.get();
1114                         p = p.next;
1115                         if (x != null) {
1116                             @SuppressWarnings("unchecked") K k =
1117                                 (K) WeakHashMap.unmaskNull(x);
1118                             action.accept(k);
1119                         }
1120                     }
1121                 } while (p != null || i < hi);
1122             }
1123             if (m.modCount != mc)
1124                 throw new ConcurrentModificationException();
1125         }
1126 
1127         public boolean tryAdvance(Consumer<? super K> action) {
1128             int hi;
1129             if (action == null)
1130                 throw new NullPointerException();
1131             WeakHashMap.Entry<K,V>[] tab = map.table;
1132             if (tab.length >= (hi = getFence()) && index >= 0) {
1133                 while (current != null || index < hi) {
1134                     if (current == null)
1135                         current = tab[index++];
1136                     else {
1137                         Object x = current.get();
1138                         current = current.next;
1139                         if (x != null) {
1140                             @SuppressWarnings("unchecked") K k =
1141                                 (K) WeakHashMap.unmaskNull(x);
1142                             action.accept(k);
1143                             if (map.modCount != expectedModCount)
1144                                 throw new ConcurrentModificationException();
1145                             return true;
1146                         }
1147                     }
1148                 }
1149             }
1150             return false;
1151         }
1152 
1153         public int characteristics() {
1154             return Spliterator.DISTINCT;
1155         }
1156     }
1157 
1158     static final class ValueSpliterator<K,V>
1159         extends WeakHashMapSpliterator<K,V>
1160         implements Spliterator<V> {
1161         ValueSpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1162                          int expectedModCount) {
1163             super(m, origin, fence, est, expectedModCount);
1164         }
1165 
1166         public ValueSpliterator<K,V> trySplit() {
1167             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1168             return (lo >= mid) ? null :
1169                 new ValueSpliterator<K,V>(map, lo, index = mid, est >>>= 1,
1170                                           expectedModCount);
1171         }
1172 
1173         public void forEachRemaining(Consumer<? super V> action) {
1174             int i, hi, mc;
1175             if (action == null)
1176                 throw new NullPointerException();
1177             WeakHashMap<K,V> m = map;
1178             WeakHashMap.Entry<K,V>[] tab = m.table;
1179             if ((hi = fence) < 0) {
1180                 mc = expectedModCount = m.modCount;
1181                 hi = fence = tab.length;
1182             }
1183             else
1184                 mc = expectedModCount;
1185             if (tab.length >= hi && (i = index) >= 0 &&
1186                 (i < (index = hi) || current != null)) {
1187                 WeakHashMap.Entry<K,V> p = current;
1188                 current = null; // exhaust
1189                 do {
1190                     if (p == null)
1191                         p = tab[i++];
1192                     else {
1193                         Object x = p.get();
1194                         V v = p.value;
1195                         p = p.next;
1196                         if (x != null)
1197                             action.accept(v);
1198                     }
1199                 } while (p != null || i < hi);
1200             }
1201             if (m.modCount != mc)
1202                 throw new ConcurrentModificationException();
1203         }
1204 
1205         public boolean tryAdvance(Consumer<? super V> action) {
1206             int hi;
1207             if (action == null)
1208                 throw new NullPointerException();
1209             WeakHashMap.Entry<K,V>[] tab = map.table;
1210             if (tab.length >= (hi = getFence()) && index >= 0) {
1211                 while (current != null || index < hi) {
1212                     if (current == null)
1213                         current = tab[index++];
1214                     else {
1215                         Object x = current.get();
1216                         V v = current.value;
1217                         current = current.next;
1218                         if (x != null) {
1219                             action.accept(v);
1220                             if (map.modCount != expectedModCount)
1221                                 throw new ConcurrentModificationException();
1222                             return true;
1223                         }
1224                     }
1225                 }
1226             }
1227             return false;
1228         }
1229 
1230         public int characteristics() {
1231             return 0;
1232         }
1233     }
1234 
1235     static final class EntrySpliterator<K,V>
1236         extends WeakHashMapSpliterator<K,V>
1237         implements Spliterator<Map.Entry<K,V>> {
1238         EntrySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1239                        int expectedModCount) {
1240             super(m, origin, fence, est, expectedModCount);
1241         }
1242 
1243         public EntrySpliterator<K,V> trySplit() {
1244             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1245             return (lo >= mid) ? null :
1246                 new EntrySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
1247                                           expectedModCount);
1248         }
1249 
1250 
1251         public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
1252             int i, hi, mc;
1253             if (action == null)
1254                 throw new NullPointerException();
1255             WeakHashMap<K,V> m = map;
1256             WeakHashMap.Entry<K,V>[] tab = m.table;
1257             if ((hi = fence) < 0) {
1258                 mc = expectedModCount = m.modCount;
1259                 hi = fence = tab.length;
1260             }
1261             else
1262                 mc = expectedModCount;
1263             if (tab.length >= hi && (i = index) >= 0 &&
1264                 (i < (index = hi) || current != null)) {
1265                 WeakHashMap.Entry<K,V> p = current;
1266                 current = null; // exhaust
1267                 do {
1268                     if (p == null)
1269                         p = tab[i++];
1270                     else {
1271                         Object x = p.get();
1272                         V v = p.value;
1273                         p = p.next;
1274                         if (x != null) {
1275                             @SuppressWarnings("unchecked") K k =
1276                                 (K) WeakHashMap.unmaskNull(x);
1277                             action.accept
1278                                 (new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
1279                         }
1280                     }
1281                 } while (p != null || i < hi);
1282             }
1283             if (m.modCount != mc)
1284                 throw new ConcurrentModificationException();
1285         }
1286 
1287         public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
1288             int hi;
1289             if (action == null)
1290                 throw new NullPointerException();
1291             WeakHashMap.Entry<K,V>[] tab = map.table;
1292             if (tab.length >= (hi = getFence()) && index >= 0) {
1293                 while (current != null || index < hi) {
1294                     if (current == null)
1295                         current = tab[index++];
1296                     else {
1297                         Object x = current.get();
1298                         V v = current.value;
1299                         current = current.next;
1300                         if (x != null) {
1301                             @SuppressWarnings("unchecked") K k =
1302                                 (K) WeakHashMap.unmaskNull(x);
1303                             action.accept
1304                                 (new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
1305                             if (map.modCount != expectedModCount)
1306                                 throw new ConcurrentModificationException();
1307                             return true;
1308                         }
1309                     }
1310                 }
1311             }
1312             return false;
1313         }
1314 
1315         public int characteristics() {
1316             return Spliterator.DISTINCT;
1317         }
1318     }
1319 
1320 }