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