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