1 /*
   2  * Copyright (c) 1998, 2010, 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 import java.lang.ref.WeakReference;
  28 import java.lang.ref.ReferenceQueue;
  29 
  30 
  31 /**
  32  * Hash table based implementation of the <tt>Map</tt> interface, with
  33  * <em>weak keys</em>.
  34  * An entry in a <tt>WeakHashMap</tt> will automatically be removed when
  35  * its key is no longer in ordinary use.  More precisely, the presence of a
  36  * mapping for a given key will not prevent the key from being discarded by the
  37  * garbage collector, that is, made finalizable, finalized, and then reclaimed.
  38  * When a key has been discarded its entry is effectively removed from the map,
  39  * so this class behaves somewhat differently from other <tt>Map</tt>
  40  * implementations.
  41  *
  42  * <p> Both null values and the null key are supported. This class has
  43  * performance characteristics similar to those of the <tt>HashMap</tt>
  44  * class, and has the same efficiency parameters of <em>initial capacity</em>
  45  * and <em>load factor</em>.
  46  *
  47  * <p> Like most collection classes, this class is not synchronized.
  48  * A synchronized <tt>WeakHashMap</tt> may be constructed using the
  49  * {@link Collections#synchronizedMap Collections.synchronizedMap}
  50  * method.
  51  *
  52  * <p> This class is intended primarily for use with key objects whose
  53  * <tt>equals</tt> methods test for object identity using the
  54  * <tt>==</tt> operator.  Once such a key is discarded it can never be
  55  * recreated, so it is impossible to do a lookup of that key in a
  56  * <tt>WeakHashMap</tt> at some later time and be surprised that its entry
  57  * has been removed.  This class will work perfectly well with key objects
  58  * whose <tt>equals</tt> methods are not based upon object identity, such
  59  * as <tt>String</tt> instances.  With such recreatable key objects,
  60  * however, the automatic removal of <tt>WeakHashMap</tt> entries whose
  61  * keys have been discarded may prove to be confusing.
  62  *
  63  * <p> The behavior of the <tt>WeakHashMap</tt> class depends in part upon
  64  * the actions of the garbage collector, so several familiar (though not
  65  * required) <tt>Map</tt> invariants do not hold for this class.  Because
  66  * the garbage collector may discard keys at any time, a
  67  * <tt>WeakHashMap</tt> may behave as though an unknown thread is silently
  68  * removing entries.  In particular, even if you synchronize on a
  69  * <tt>WeakHashMap</tt> instance and invoke none of its mutator methods, it
  70  * is possible for the <tt>size</tt> method to return smaller values over
  71  * time, for the <tt>isEmpty</tt> method to return <tt>false</tt> and
  72  * then <tt>true</tt>, for the <tt>containsKey</tt> method to return
  73  * <tt>true</tt> and later <tt>false</tt> for a given key, for the
  74  * <tt>get</tt> method to return a value for a given key but later return
  75  * <tt>null</tt>, for the <tt>put</tt> method to return
  76  * <tt>null</tt> and the <tt>remove</tt> method to return
  77  * <tt>false</tt> for a key that previously appeared to be in the map, and
  78  * for successive examinations of the key set, the value collection, and
  79  * the entry set to yield successively smaller numbers of elements.
  80  *
  81  * <p> Each key object in a <tt>WeakHashMap</tt> is stored indirectly as
  82  * the referent of a weak reference.  Therefore a key will automatically be
  83  * removed only after the weak references to it, both inside and outside of the
  84  * map, have been cleared by the garbage collector.
  85  *
  86  * <p> <strong>Implementation note:</strong> The value objects in a
  87  * <tt>WeakHashMap</tt> are held by ordinary strong references.  Thus care
  88  * should be taken to ensure that value objects do not strongly refer to their
  89  * own keys, either directly or indirectly, since that will prevent the keys
  90  * from being discarded.  Note that a value object may refer indirectly to its
  91  * key via the <tt>WeakHashMap</tt> itself; that is, a value object may
  92  * strongly refer to some other key object whose associated value object, in
  93  * turn, strongly refers to the key of the first value object.  One way
  94  * to deal with this is to wrap values themselves within
  95  * <tt>WeakReferences</tt> before
  96  * inserting, as in: <tt>m.put(key, new WeakReference(value))</tt>,
  97  * and then unwrapping upon each <tt>get</tt>.
  98  *
  99  * <p>The iterators returned by the <tt>iterator</tt> method of the collections
 100  * returned by all of this class's "collection view methods" are
 101  * <i>fail-fast</i>: if the map is structurally modified at any time after the
 102  * iterator is created, in any way except through the iterator's own
 103  * <tt>remove</tt> method, the iterator will throw a {@link
 104  * ConcurrentModificationException}.  Thus, in the face of concurrent
 105  * modification, the iterator fails quickly and cleanly, rather than risking
 106  * arbitrary, non-deterministic behavior at an undetermined time in the future.
 107  *
 108  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
 109  * as it is, generally speaking, impossible to make any hard guarantees in the
 110  * presence of unsynchronized concurrent modification.  Fail-fast iterators
 111  * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
 112  * Therefore, it would be wrong to write a program that depended on this
 113  * exception for its correctness:  <i>the fail-fast behavior of iterators
 114  * should be used only to detect bugs.</i>
 115  *
 116  * <p>This class is a member of the
 117  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 118  * Java Collections Framework</a>.
 119  *
 120  * @param <K> the type of keys maintained by this map
 121  * @param <V> the type of mapped values
 122  *
 123  * @author      Doug Lea
 124  * @author      Josh Bloch
 125  * @author      Mark Reinhold
 126  * @since       1.2
 127  * @see         java.util.HashMap
 128  * @see         java.lang.ref.WeakReference
 129  */
 130 public class WeakHashMap<K,V>
 131     extends AbstractMap<K,V>
 132     implements Map<K,V> {
 133 
 134     /**
 135      * The default initial capacity -- MUST be a power of two.
 136      */
 137     private static final int DEFAULT_INITIAL_CAPACITY = 16;
 138 
 139     /**
 140      * The maximum capacity, used if a higher value is implicitly specified
 141      * by either of the constructors with arguments.
 142      * MUST be a power of two <= 1<<30.
 143      */
 144     private static final int MAXIMUM_CAPACITY = 1 << 30;
 145 
 146     /**
 147      * The load factor used when none specified in constructor.
 148      */
 149     private static final float DEFAULT_LOAD_FACTOR = 0.75f;
 150 
 151     /**
 152      * The table, resized as necessary. Length MUST Always be a power of two.
 153      */
 154     Entry<K,V>[] table;
 155 
 156     /**
 157      * The number of key-value mappings contained in this weak hash map.
 158      */
 159     private int size;
 160 
 161     /**
 162      * The next size value at which to resize (capacity * load factor).
 163      */
 164     private int threshold;
 165 
 166     /**
 167      * The load factor for the hash table.
 168      */
 169     private final float loadFactor;
 170 
 171     /**
 172      * Reference queue for cleared WeakEntries
 173      */
 174     private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
 175 
 176     /**
 177      * The number of times this WeakHashMap has been structurally modified.
 178      * Structural modifications are those that change the number of
 179      * mappings in the map or otherwise modify its internal structure
 180      * (e.g., rehash).  This field is used to make iterators on
 181      * Collection-views of the map fail-fast.
 182      *
 183      * @see ConcurrentModificationException
 184      */
 185     int modCount;
 186 
 187     /**
 188      * A randomizing value associated with this instance that is applied to
 189      * hash code of keys to make hash collisions harder to find.
 190      */
 191     transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this);
 192 
 193     @SuppressWarnings("unchecked")
 194     private Entry<K,V>[] newTable(int n) {
 195         return (Entry<K,V>[]) new Entry<?,?>[n];
 196     }
 197 
 198     /**
 199      * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial
 200      * capacity and the given load factor.
 201      *
 202      * @param  initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
 203      * @param  loadFactor      The load factor of the <tt>WeakHashMap</tt>
 204      * @throws IllegalArgumentException if the initial capacity is negative,
 205      *         or if the load factor is nonpositive.
 206      */
 207     public WeakHashMap(int initialCapacity, float loadFactor) {
 208         if (initialCapacity < 0)
 209             throw new IllegalArgumentException("Illegal Initial Capacity: "+
 210                                                initialCapacity);
 211         if (initialCapacity > MAXIMUM_CAPACITY)
 212             initialCapacity = MAXIMUM_CAPACITY;
 213 
 214         if (loadFactor <= 0 || Float.isNaN(loadFactor))
 215             throw new IllegalArgumentException("Illegal Load factor: "+
 216                                                loadFactor);
 217         int capacity = 1;
 218         while (capacity < initialCapacity)
 219             capacity <<= 1;
 220         table = newTable(capacity);
 221         this.loadFactor = loadFactor;
 222         threshold = (int)(capacity * loadFactor);
 223     }
 224 
 225     /**
 226      * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial
 227      * capacity and the default load factor (0.75).
 228      *
 229      * @param  initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
 230      * @throws IllegalArgumentException if the initial capacity is negative
 231      */
 232     public WeakHashMap(int initialCapacity) {
 233         this(initialCapacity, DEFAULT_LOAD_FACTOR);
 234     }
 235 
 236     /**
 237      * Constructs a new, empty <tt>WeakHashMap</tt> with the default initial
 238      * capacity (16) and load factor (0.75).
 239      */
 240     public WeakHashMap() {
 241         this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
 242     }
 243 
 244     /**
 245      * Constructs a new <tt>WeakHashMap</tt> with the same mappings as the
 246      * specified map.  The <tt>WeakHashMap</tt> is created with the default
 247      * load factor (0.75) and an initial capacity sufficient to hold the
 248      * mappings in the specified map.
 249      *
 250      * @param   m the map whose mappings are to be placed in this map
 251      * @throws  NullPointerException if the specified map is null
 252      * @since   1.3
 253      */
 254     public WeakHashMap(Map<? extends K, ? extends V> m) {
 255         this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
 256                 DEFAULT_INITIAL_CAPACITY),
 257              DEFAULT_LOAD_FACTOR);
 258         putAll(m);
 259     }
 260 
 261     // internal utilities
 262 
 263     /**
 264      * Value representing null keys inside tables.
 265      */
 266     private static final Object NULL_KEY = new Object();
 267 
 268     /**
 269      * Use NULL_KEY for key if it is null.
 270      */
 271     private static Object maskNull(Object key) {
 272         return (key == null) ? NULL_KEY : key;
 273     }
 274 
 275     /**
 276      * Returns internal representation of null key back to caller as null.
 277      */
 278     static Object unmaskNull(Object key) {
 279         return (key == NULL_KEY) ? null : key;
 280     }
 281 
 282     /**
 283      * Checks for equality of non-null reference x and possibly-null y.  By
 284      * default uses Object.equals.
 285      */
 286     private static boolean eq(Object x, Object y) {
 287         return x == y || x.equals(y);
 288     }
 289 
 290     /**
 291      * Retrieve object hash code and applies a supplemental hash function to the
 292      * result hash, which defends against poor quality hash functions.  This is
 293      * critical because HashMap uses power-of-two length hash tables, that
 294      * otherwise encounter collisions for hashCodes that do not differ
 295      * in lower bits.
 296      */
 297     final int hash(Object k) {
 298         if (k instanceof String) {
 299             return ((String) k).hash32();
 300         }
 301         int  h = hashSeed ^ k.hashCode();
 302 
 303         // This function ensures that hashCodes that differ only by
 304         // constant multiples at each bit position have a bounded
 305         // number of collisions (approximately 8 at default load factor).
 306         h ^= (h >>> 20) ^ (h >>> 12);
 307         return h ^ (h >>> 7) ^ (h >>> 4);
 308     }
 309 
 310     /**
 311      * Returns index for hash code h.
 312      */
 313     private static int indexFor(int h, int length) {
 314         return h & (length-1);
 315     }
 316 
 317     /**
 318      * Expunges stale entries from the table.
 319      */
 320     private void expungeStaleEntries() {
 321         for (Object x; (x = queue.poll()) != null; ) {
 322             synchronized (queue) {
 323                 @SuppressWarnings("unchecked")
 324                     Entry<K,V> e = (Entry<K,V>) x;
 325                 int i = indexFor(e.hash, table.length);
 326 
 327                 Entry<K,V> prev = table[i];
 328                 Entry<K,V> p = prev;
 329                 while (p != null) {
 330                     Entry<K,V> next = p.next;
 331                     if (p == e) {
 332                         if (prev == e)
 333                             table[i] = next;
 334                         else
 335                             prev.next = next;
 336                         // Must not null out e.next;
 337                         // stale entries may be in use by a HashIterator
 338                         e.value = null; // Help GC
 339                         size--;
 340                         break;
 341                     }
 342                     prev = p;
 343                     p = next;
 344                 }
 345             }
 346         }
 347     }
 348 
 349     /**
 350      * Returns the table after first expunging stale entries.
 351      */
 352     private Entry<K,V>[] getTable() {
 353         expungeStaleEntries();
 354         return table;
 355     }
 356 
 357     /**
 358      * Returns the number of key-value mappings in this map.
 359      * This result is a snapshot, and may not reflect unprocessed
 360      * entries that will be removed before next attempted access
 361      * because they are no longer referenced.
 362      */
 363     public int size() {
 364         if (size == 0)
 365             return 0;
 366         expungeStaleEntries();
 367         return size;
 368     }
 369 
 370     /**
 371      * Returns <tt>true</tt> if this map contains no key-value mappings.
 372      * This result is a snapshot, and may not reflect unprocessed
 373      * entries that will be removed before next attempted access
 374      * because they are no longer referenced.
 375      */
 376     public boolean isEmpty() {
 377         return size() == 0;
 378     }
 379 
 380     /**
 381      * Returns the value to which the specified key is mapped,
 382      * or {@code null} if this map contains no mapping for the key.
 383      *
 384      * <p>More formally, if this map contains a mapping from a key
 385      * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
 386      * key.equals(k))}, then this method returns {@code v}; otherwise
 387      * it returns {@code null}.  (There can be at most one such mapping.)
 388      *
 389      * <p>A return value of {@code null} does not <i>necessarily</i>
 390      * indicate that the map contains no mapping for the key; it's also
 391      * possible that the map explicitly maps the key to {@code null}.
 392      * The {@link #containsKey containsKey} operation may be used to
 393      * distinguish these two cases.
 394      *
 395      * @see #put(Object, Object)
 396      */
 397     public V get(Object key) {
 398         Object k = maskNull(key);
 399         int h = hash(k);
 400         Entry<K,V>[] tab = getTable();
 401         int index = indexFor(h, tab.length);
 402         Entry<K,V> e = tab[index];
 403         while (e != null) {
 404             if (e.hash == h && eq(k, e.get()))
 405                 return e.value;
 406             e = e.next;
 407         }
 408         return null;
 409     }
 410 
 411     /**
 412      * Returns <tt>true</tt> if this map contains a mapping for the
 413      * specified key.
 414      *
 415      * @param  key   The key whose presence in this map is to be tested
 416      * @return <tt>true</tt> if there is a mapping for <tt>key</tt>;
 417      *         <tt>false</tt> otherwise
 418      */
 419     public boolean containsKey(Object key) {
 420         return getEntry(key) != null;
 421     }
 422 
 423     /**
 424      * Returns the entry associated with the specified key in this map.
 425      * Returns null if the map contains no mapping for this key.
 426      */
 427     Entry<K,V> getEntry(Object key) {
 428         Object k = maskNull(key);
 429         int h = hash(k);
 430         Entry<K,V>[] tab = getTable();
 431         int index = indexFor(h, tab.length);
 432         Entry<K,V> e = tab[index];
 433         while (e != null && !(e.hash == h && eq(k, e.get())))
 434             e = e.next;
 435         return e;
 436     }
 437 
 438     /**
 439      * Associates the specified value with the specified key in this map.
 440      * If the map previously contained a mapping for this key, the old
 441      * value is replaced.
 442      *
 443      * @param key key with which the specified value is to be associated.
 444      * @param value value to be associated with the specified key.
 445      * @return the previous value associated with <tt>key</tt>, or
 446      *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 447      *         (A <tt>null</tt> return can also indicate that the map
 448      *         previously associated <tt>null</tt> with <tt>key</tt>.)
 449      */
 450     public V put(K key, V value) {
 451         Object k = maskNull(key);
 452         int h = hash(k);
 453         Entry<K,V>[] tab = getTable();
 454         int i = indexFor(h, tab.length);
 455 
 456         for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
 457             if (h == e.hash && eq(k, e.get())) {
 458                 V oldValue = e.value;
 459                 if (value != oldValue)
 460                     e.value = value;
 461                 return oldValue;
 462             }
 463         }
 464 
 465         modCount++;
 466         Entry<K,V> e = tab[i];
 467         tab[i] = new Entry<>(k, value, queue, h, e);
 468         if (++size >= threshold)
 469             resize(tab.length * 2);
 470         return null;
 471     }
 472 
 473     /**
 474      * Rehashes the contents of this map into a new array with a
 475      * larger capacity.  This method is called automatically when the
 476      * number of keys in this map reaches its threshold.
 477      *
 478      * If current capacity is MAXIMUM_CAPACITY, this method does not
 479      * resize the map, but sets threshold to Integer.MAX_VALUE.
 480      * This has the effect of preventing future calls.
 481      *
 482      * @param newCapacity the new capacity, MUST be a power of two;
 483      *        must be greater than current capacity unless current
 484      *        capacity is MAXIMUM_CAPACITY (in which case value
 485      *        is irrelevant).
 486      */
 487     void resize(int newCapacity) {
 488         Entry<K,V>[] oldTable = getTable();
 489         int oldCapacity = oldTable.length;
 490         if (oldCapacity == MAXIMUM_CAPACITY) {
 491             threshold = Integer.MAX_VALUE;
 492             return;
 493         }
 494 
 495         Entry<K,V>[] newTable = newTable(newCapacity);
 496         transfer(oldTable, newTable);
 497         table = newTable;
 498 
 499         /*
 500          * If ignoring null elements and processing ref queue caused massive
 501          * shrinkage, then restore old table.  This should be rare, but avoids
 502          * unbounded expansion of garbage-filled tables.
 503          */
 504         if (size >= threshold / 2) {
 505             threshold = (int)(newCapacity * loadFactor);
 506         } else {
 507             expungeStaleEntries();
 508             transfer(newTable, oldTable);
 509             table = oldTable;
 510         }
 511     }
 512 
 513     /** Transfers all entries from src to dest tables */
 514     private void transfer(Entry<K,V>[] src, Entry<K,V>[] dest) {
 515         for (int j = 0; j < src.length; ++j) {
 516             Entry<K,V> e = src[j];
 517             src[j] = null;
 518             while (e != null) {
 519                 Entry<K,V> next = e.next;
 520                 Object key = e.get();
 521                 if (key == null) {
 522                     e.next = null;  // Help GC
 523                     e.value = null; //  "   "
 524                     size--;
 525                 } else {
 526                     int i = indexFor(e.hash, dest.length);
 527                     e.next = dest[i];
 528                     dest[i] = e;
 529                 }
 530                 e = next;
 531             }
 532         }
 533     }
 534 
 535     /**
 536      * Copies all of the mappings from the specified map to this map.
 537      * These mappings will replace any mappings that this map had for any
 538      * of the keys currently in the specified map.
 539      *
 540      * @param m mappings to be stored in this map.
 541      * @throws  NullPointerException if the specified map is null.
 542      */
 543     public void putAll(Map<? extends K, ? extends V> m) {
 544         int numKeysToBeAdded = m.size();
 545         if (numKeysToBeAdded == 0)
 546             return;
 547 
 548         /*
 549          * Expand the map if the map if the number of mappings to be added
 550          * is greater than or equal to threshold.  This is conservative; the
 551          * obvious condition is (m.size() + size) >= threshold, but this
 552          * condition could result in a map with twice the appropriate capacity,
 553          * if the keys to be added overlap with the keys already in this map.
 554          * By using the conservative calculation, we subject ourself
 555          * to at most one extra resize.
 556          */
 557         if (numKeysToBeAdded > threshold) {
 558             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
 559             if (targetCapacity > MAXIMUM_CAPACITY)
 560                 targetCapacity = MAXIMUM_CAPACITY;
 561             int newCapacity = table.length;
 562             while (newCapacity < targetCapacity)
 563                 newCapacity <<= 1;
 564             if (newCapacity > table.length)
 565                 resize(newCapacity);
 566         }
 567 
 568         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
 569             put(e.getKey(), e.getValue());
 570     }
 571 
 572     /**
 573      * Removes the mapping for a key from this weak hash map if it is present.
 574      * More formally, if this map contains a mapping from key <tt>k</tt> to
 575      * value <tt>v</tt> such that <code>(key==null ?  k==null :
 576      * key.equals(k))</code>, that mapping is removed.  (The map can contain
 577      * at most one such mapping.)
 578      *
 579      * <p>Returns the value to which this map previously associated the key,
 580      * or <tt>null</tt> if the map contained no mapping for the key.  A
 581      * return value of <tt>null</tt> does not <i>necessarily</i> indicate
 582      * that the map contained no mapping for the key; it's also possible
 583      * that the map explicitly mapped the key to <tt>null</tt>.
 584      *
 585      * <p>The map will not contain a mapping for the specified key once the
 586      * call returns.
 587      *
 588      * @param key key whose mapping is to be removed from the map
 589      * @return the previous value associated with <tt>key</tt>, or
 590      *         <tt>null</tt> if there was no mapping for <tt>key</tt>
 591      */
 592     public V remove(Object key) {
 593         Object k = maskNull(key);
 594         int h = hash(k);
 595         Entry<K,V>[] tab = getTable();
 596         int i = indexFor(h, tab.length);
 597         Entry<K,V> prev = tab[i];
 598         Entry<K,V> e = prev;
 599 
 600         while (e != null) {
 601             Entry<K,V> next = e.next;
 602             if (h == e.hash && eq(k, e.get())) {
 603                 modCount++;
 604                 size--;
 605                 if (prev == e)
 606                     tab[i] = next;
 607                 else
 608                     prev.next = next;
 609                 return e.value;
 610             }
 611             prev = e;
 612             e = next;
 613         }
 614 
 615         return null;
 616     }
 617 
 618     /** Special version of remove needed by Entry set */
 619     boolean removeMapping(Object o) {
 620         if (!(o instanceof Map.Entry))
 621             return false;
 622         Entry<K,V>[] tab = getTable();
 623         Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
 624         Object k = maskNull(entry.getKey());
 625         int h = hash(k);
 626         int i = indexFor(h, tab.length);
 627         Entry<K,V> prev = tab[i];
 628         Entry<K,V> e = prev;
 629 
 630         while (e != null) {
 631             Entry<K,V> next = e.next;
 632             if (h == e.hash && e.equals(entry)) {
 633                 modCount++;
 634                 size--;
 635                 if (prev == e)
 636                     tab[i] = next;
 637                 else
 638                     prev.next = next;
 639                 return true;
 640             }
 641             prev = e;
 642             e = next;
 643         }
 644 
 645         return false;
 646     }
 647 
 648     /**
 649      * Removes all of the mappings from this map.
 650      * The map will be empty after this call returns.
 651      */
 652     public void clear() {
 653         // clear out ref queue. We don't need to expunge entries
 654         // since table is getting cleared.
 655         while (queue.poll() != null)
 656             ;
 657 
 658         modCount++;
 659         Arrays.fill(table, null);
 660         size = 0;
 661 
 662         // Allocation of array may have caused GC, which may have caused
 663         // additional entries to go stale.  Removing these entries from the
 664         // reference queue will make them eligible for reclamation.
 665         while (queue.poll() != null)
 666             ;
 667     }
 668 
 669     /**
 670      * Returns <tt>true</tt> if this map maps one or more keys to the
 671      * specified value.
 672      *
 673      * @param value value whose presence in this map is to be tested
 674      * @return <tt>true</tt> if this map maps one or more keys to the
 675      *         specified value
 676      */
 677     public boolean containsValue(Object value) {
 678         if (value==null)
 679             return containsNullValue();
 680 
 681         Entry<K,V>[] tab = getTable();
 682         for (int i = tab.length; i-- > 0;)
 683             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
 684                 if (value.equals(e.value))
 685                     return true;
 686         return false;
 687     }
 688 
 689     /**
 690      * Special-case code for containsValue with null argument
 691      */
 692     private boolean containsNullValue() {
 693         Entry<K,V>[] tab = getTable();
 694         for (int i = tab.length; i-- > 0;)
 695             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
 696                 if (e.value==null)
 697                     return true;
 698         return false;
 699     }
 700 
 701     /**
 702      * The entries in this hash table extend WeakReference, using its main ref
 703      * field as the key.
 704      */
 705     private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
 706         V value;
 707         final int hash;
 708         Entry<K,V> next;
 709 
 710         /**
 711          * Creates new entry.
 712          */
 713         Entry(Object key, V value,
 714               ReferenceQueue<Object> queue,
 715               int hash, Entry<K,V> next) {
 716             super(key, queue);
 717             this.value = value;
 718             this.hash  = hash;
 719             this.next  = next;
 720         }
 721 
 722         @SuppressWarnings("unchecked")
 723         public K getKey() {
 724             return (K) WeakHashMap.unmaskNull(get());
 725         }
 726 
 727         public V getValue() {
 728             return value;
 729         }
 730 
 731         public V setValue(V newValue) {
 732             V oldValue = value;
 733             value = newValue;
 734             return oldValue;
 735         }
 736 
 737         public boolean equals(Object o) {
 738             if (!(o instanceof Map.Entry))
 739                 return false;
 740             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
 741             K k1 = getKey();
 742             Object k2 = e.getKey();
 743             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
 744                 V v1 = getValue();
 745                 Object v2 = e.getValue();
 746                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
 747                     return true;
 748             }
 749             return false;
 750         }
 751 
 752         public int hashCode() {
 753             K k = getKey();
 754             V v = getValue();
 755             return ((k==null ? 0 : k.hashCode()) ^
 756                     (v==null ? 0 : v.hashCode()));
 757         }
 758 
 759         public String toString() {
 760             return getKey() + "=" + getValue();
 761         }
 762     }
 763 
 764     private abstract class HashIterator<T> implements Iterator<T> {
 765         private int index;
 766         private Entry<K,V> entry = null;
 767         private Entry<K,V> lastReturned = null;
 768         private int expectedModCount = modCount;
 769 
 770         /**
 771          * Strong reference needed to avoid disappearance of key
 772          * between hasNext and next
 773          */
 774         private Object nextKey = null;
 775 
 776         /**
 777          * Strong reference needed to avoid disappearance of key
 778          * between nextEntry() and any use of the entry
 779          */
 780         private Object currentKey = null;
 781 
 782         HashIterator() {
 783             index = isEmpty() ? 0 : table.length;
 784         }
 785 
 786         public boolean hasNext() {
 787             Entry<K,V>[] t = table;
 788 
 789             while (nextKey == null) {
 790                 Entry<K,V> e = entry;
 791                 int i = index;
 792                 while (e == null && i > 0)
 793                     e = t[--i];
 794                 entry = e;
 795                 index = i;
 796                 if (e == null) {
 797                     currentKey = null;
 798                     return false;
 799                 }
 800                 nextKey = e.get(); // hold on to key in strong ref
 801                 if (nextKey == null)
 802                     entry = entry.next;
 803             }
 804             return true;
 805         }
 806 
 807         /** The common parts of next() across different types of iterators */
 808         protected Entry<K,V> nextEntry() {
 809             if (modCount != expectedModCount)
 810                 throw new ConcurrentModificationException();
 811             if (nextKey == null && !hasNext())
 812                 throw new NoSuchElementException();
 813 
 814             lastReturned = entry;
 815             entry = entry.next;
 816             currentKey = nextKey;
 817             nextKey = null;
 818             return lastReturned;
 819         }
 820 
 821         public void remove() {
 822             if (lastReturned == null)
 823                 throw new IllegalStateException();
 824             if (modCount != expectedModCount)
 825                 throw new ConcurrentModificationException();
 826 
 827             WeakHashMap.this.remove(currentKey);
 828             expectedModCount = modCount;
 829             lastReturned = null;
 830             currentKey = null;
 831         }
 832 
 833     }
 834 
 835     private class ValueIterator extends HashIterator<V> {
 836         public V next() {
 837             return nextEntry().value;
 838         }
 839     }
 840 
 841     private class KeyIterator extends HashIterator<K> {
 842         public K next() {
 843             return nextEntry().getKey();
 844         }
 845     }
 846 
 847     private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
 848         public Map.Entry<K,V> next() {
 849             return nextEntry();
 850         }
 851     }
 852 
 853     // Views
 854 
 855     private transient Set<Map.Entry<K,V>> entrySet = null;
 856 
 857     /**
 858      * Returns a {@link Set} view of the keys contained in this map.
 859      * The set is backed by the map, so changes to the map are
 860      * reflected in the set, and vice-versa.  If the map is modified
 861      * while an iteration over the set is in progress (except through
 862      * the iterator's own <tt>remove</tt> operation), the results of
 863      * the iteration are undefined.  The set supports element removal,
 864      * which removes the corresponding mapping from the map, via the
 865      * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
 866      * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
 867      * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
 868      * operations.
 869      */
 870     public Set<K> keySet() {
 871         Set<K> ks = keySet;
 872         return (ks != null ? ks : (keySet = new KeySet()));
 873     }
 874 
 875     private class KeySet extends AbstractSet<K> {
 876         public Iterator<K> iterator() {
 877             return new KeyIterator();
 878         }
 879 
 880         public int size() {
 881             return WeakHashMap.this.size();
 882         }
 883 
 884         public boolean contains(Object o) {
 885             return containsKey(o);
 886         }
 887 
 888         public boolean remove(Object o) {
 889             if (containsKey(o)) {
 890                 WeakHashMap.this.remove(o);
 891                 return true;
 892             }
 893             else
 894                 return false;
 895         }
 896 
 897         public void clear() {
 898             WeakHashMap.this.clear();
 899         }
 900     }
 901 
 902     /**
 903      * Returns a {@link Collection} view of the values contained in this map.
 904      * The collection is backed by the map, so changes to the map are
 905      * reflected in the collection, and vice-versa.  If the map is
 906      * modified while an iteration over the collection is in progress
 907      * (except through the iterator's own <tt>remove</tt> operation),
 908      * the results of the iteration are undefined.  The collection
 909      * supports element removal, which removes the corresponding
 910      * mapping from the map, via the <tt>Iterator.remove</tt>,
 911      * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
 912      * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
 913      * support the <tt>add</tt> or <tt>addAll</tt> operations.
 914      */
 915     public Collection<V> values() {
 916         Collection<V> vs = values;
 917         return (vs != null) ? vs : (values = new Values());
 918     }
 919 
 920     private class Values extends AbstractCollection<V> {
 921         public Iterator<V> iterator() {
 922             return new ValueIterator();
 923         }
 924 
 925         public int size() {
 926             return WeakHashMap.this.size();
 927         }
 928 
 929         public boolean contains(Object o) {
 930             return containsValue(o);
 931         }
 932 
 933         public void clear() {
 934             WeakHashMap.this.clear();
 935         }
 936     }
 937 
 938     /**
 939      * Returns a {@link Set} view of the mappings contained in this map.
 940      * The set is backed by the map, so changes to the map are
 941      * reflected in the set, and vice-versa.  If the map is modified
 942      * while an iteration over the set is in progress (except through
 943      * the iterator's own <tt>remove</tt> operation, or through the
 944      * <tt>setValue</tt> operation on a map entry returned by the
 945      * iterator) the results of the iteration are undefined.  The set
 946      * supports element removal, which removes the corresponding
 947      * mapping from the map, via the <tt>Iterator.remove</tt>,
 948      * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
 949      * <tt>clear</tt> operations.  It does not support the
 950      * <tt>add</tt> or <tt>addAll</tt> operations.
 951      */
 952     public Set<Map.Entry<K,V>> entrySet() {
 953         Set<Map.Entry<K,V>> es = entrySet;
 954         return es != null ? es : (entrySet = new EntrySet());
 955     }
 956 
 957     private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
 958         public Iterator<Map.Entry<K,V>> iterator() {
 959             return new EntryIterator();
 960         }
 961 
 962         public boolean contains(Object o) {
 963             if (!(o instanceof Map.Entry))
 964                 return false;
 965             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
 966             Entry<K,V> candidate = getEntry(e.getKey());
 967             return candidate != null && candidate.equals(e);
 968         }
 969 
 970         public boolean remove(Object o) {
 971             return removeMapping(o);
 972         }
 973 
 974         public int size() {
 975             return WeakHashMap.this.size();
 976         }
 977 
 978         public void clear() {
 979             WeakHashMap.this.clear();
 980         }
 981 
 982         private List<Map.Entry<K,V>> deepCopy() {
 983             List<Map.Entry<K,V>> list = new ArrayList<>(size());
 984             for (Map.Entry<K,V> e : this)
 985                 list.add(new AbstractMap.SimpleEntry<>(e));
 986             return list;
 987         }
 988 
 989         public Object[] toArray() {
 990             return deepCopy().toArray();
 991         }
 992 
 993         public <T> T[] toArray(T[] a) {
 994             return deepCopy().toArray(a);
 995         }
 996     }
 997 }