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     int hash(Object k) {
 298         int h = hashSeed;
 299         if (k instanceof String) {
 300             return ((String) k).hash32();
 301         } else {
 302             h ^= k.hashCode();
 303         }
 304         
 305         // This function ensures that hashCodes that differ only by
 306         // constant multiples at each bit position have a bounded
 307         // number of collisions (approximately 8 at default load factor).
 308         h ^= (h >>> 20) ^ (h >>> 12);
 309         return h ^ (h >>> 7) ^ (h >>> 4);
 310     }
 311     
 312     /**
 313      * Returns index for hash code h.
 314      */
 315     private static int indexFor(int h, int length) {
 316         return h & (length-1);
 317     }
 318 
 319     /**
 320      * Expunges stale entries from the table.
 321      */
 322     private void expungeStaleEntries() {
 323         for (Object x; (x = queue.poll()) != null; ) {
 324             synchronized (queue) {
 325                 @SuppressWarnings("unchecked")
 326                     Entry<K,V> e = (Entry<K,V>) x;
 327                 int i = indexFor(e.hash, table.length);
 328 
 329                 Entry<K,V> prev = table[i];
 330                 Entry<K,V> p = prev;
 331                 while (p != null) {
 332                     Entry<K,V> next = p.next;
 333                     if (p == e) {
 334                         if (prev == e)
 335                             table[i] = next;
 336                         else
 337                             prev.next = next;
 338                         // Must not null out e.next;
 339                         // stale entries may be in use by a HashIterator
 340                         e.value = null; // Help GC
 341                         size--;
 342                         break;
 343                     }
 344                     prev = p;
 345                     p = next;
 346                 }
 347             }
 348         }
 349     }
 350 
 351     /**
 352      * Returns the table after first expunging stale entries.
 353      */
 354     private Entry<K,V>[] getTable() {
 355         expungeStaleEntries();
 356         return table;
 357     }
 358 
 359     /**
 360      * Returns the number of key-value mappings in this map.
 361      * This result is a snapshot, and may not reflect unprocessed
 362      * entries that will be removed before next attempted access
 363      * because they are no longer referenced.
 364      */
 365     public int size() {
 366         if (size == 0)
 367             return 0;
 368         expungeStaleEntries();
 369         return size;
 370     }
 371 
 372     /**
 373      * Returns <tt>true</tt> if this map contains no key-value mappings.
 374      * This result is a snapshot, and may not reflect unprocessed
 375      * entries that will be removed before next attempted access
 376      * because they are no longer referenced.
 377      */
 378     public boolean isEmpty() {
 379         return size() == 0;
 380     }
 381 
 382     /**
 383      * Returns the value to which the specified key is mapped,
 384      * or {@code null} if this map contains no mapping for the key.
 385      *
 386      * <p>More formally, if this map contains a mapping from a key
 387      * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
 388      * key.equals(k))}, then this method returns {@code v}; otherwise
 389      * it returns {@code null}.  (There can be at most one such mapping.)
 390      *
 391      * <p>A return value of {@code null} does not <i>necessarily</i>
 392      * indicate that the map contains no mapping for the key; it's also
 393      * possible that the map explicitly maps the key to {@code null}.
 394      * The {@link #containsKey containsKey} operation may be used to
 395      * distinguish these two cases.
 396      *
 397      * @see #put(Object, Object)
 398      */
 399     public V get(Object key) {
 400         Object k = maskNull(key);
 401         int h = hash(k);
 402         Entry<K,V>[] tab = getTable();
 403         int index = indexFor(h, tab.length);
 404         Entry<K,V> e = tab[index];
 405         while (e != null) {
 406             if (e.hash == h && eq(k, e.get()))
 407                 return e.value;
 408             e = e.next;
 409         }
 410         return null;
 411     }
 412 
 413     /**
 414      * Returns <tt>true</tt> if this map contains a mapping for the
 415      * specified key.
 416      *
 417      * @param  key   The key whose presence in this map is to be tested
 418      * @return <tt>true</tt> if there is a mapping for <tt>key</tt>;
 419      *         <tt>false</tt> otherwise
 420      */
 421     public boolean containsKey(Object key) {
 422         return getEntry(key) != null;
 423     }
 424 
 425     /**
 426      * Returns the entry associated with the specified key in this map.
 427      * Returns null if the map contains no mapping for this key.
 428      */
 429     Entry<K,V> getEntry(Object key) {
 430         Object k = maskNull(key);
 431         int h = hash(k);
 432         Entry<K,V>[] tab = getTable();
 433         int index = indexFor(h, tab.length);
 434         Entry<K,V> e = tab[index];
 435         while (e != null && !(e.hash == h && eq(k, e.get())))
 436             e = e.next;
 437         return e;
 438     }
 439 
 440     /**
 441      * Associates the specified value with the specified key in this map.
 442      * If the map previously contained a mapping for this key, the old
 443      * value is replaced.
 444      *
 445      * @param key key with which the specified value is to be associated.
 446      * @param value value to be associated with the specified key.
 447      * @return the previous value associated with <tt>key</tt>, or
 448      *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 449      *         (A <tt>null</tt> return can also indicate that the map
 450      *         previously associated <tt>null</tt> with <tt>key</tt>.)
 451      */
 452     public V put(K key, V value) {
 453         Object k = maskNull(key);
 454         int h = hash(k);
 455         Entry<K,V>[] tab = getTable();
 456         int i = indexFor(h, tab.length);
 457 
 458         for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
 459             if (h == e.hash && eq(k, e.get())) {
 460                 V oldValue = e.value;
 461                 if (value != oldValue)
 462                     e.value = value;
 463                 return oldValue;
 464             }
 465         }
 466 
 467         modCount++;
 468         Entry<K,V> e = tab[i];
 469         tab[i] = new Entry<>(k, value, queue, h, e);
 470         if (++size >= threshold)
 471             resize(tab.length * 2);
 472         return null;
 473     }
 474 
 475     /**
 476      * Rehashes the contents of this map into a new array with a
 477      * larger capacity.  This method is called automatically when the
 478      * number of keys in this map reaches its threshold.
 479      *
 480      * If current capacity is MAXIMUM_CAPACITY, this method does not
 481      * resize the map, but sets threshold to Integer.MAX_VALUE.
 482      * This has the effect of preventing future calls.
 483      *
 484      * @param newCapacity the new capacity, MUST be a power of two;
 485      *        must be greater than current capacity unless current
 486      *        capacity is MAXIMUM_CAPACITY (in which case value
 487      *        is irrelevant).
 488      */
 489     void resize(int newCapacity) {
 490         Entry<K,V>[] oldTable = getTable();
 491         int oldCapacity = oldTable.length;
 492         if (oldCapacity == MAXIMUM_CAPACITY) {
 493             threshold = Integer.MAX_VALUE;
 494             return;
 495         }
 496 
 497         Entry<K,V>[] newTable = newTable(newCapacity);
 498         transfer(oldTable, newTable);
 499         table = newTable;
 500 
 501         /*
 502          * If ignoring null elements and processing ref queue caused massive
 503          * shrinkage, then restore old table.  This should be rare, but avoids
 504          * unbounded expansion of garbage-filled tables.
 505          */
 506         if (size >= threshold / 2) {
 507             threshold = (int)(newCapacity * loadFactor);
 508         } else {
 509             expungeStaleEntries();
 510             transfer(newTable, oldTable);
 511             table = oldTable;
 512         }
 513     }
 514 
 515     /** Transfers all entries from src to dest tables */
 516     private void transfer(Entry<K,V>[] src, Entry<K,V>[] dest) {
 517         for (int j = 0; j < src.length; ++j) {
 518             Entry<K,V> e = src[j];
 519             src[j] = null;
 520             while (e != null) {
 521                 Entry<K,V> next = e.next;
 522                 Object key = e.get();
 523                 if (key == null) {
 524                     e.next = null;  // Help GC
 525                     e.value = null; //  "   "
 526                     size--;
 527                 } else {
 528                     int i = indexFor(e.hash, dest.length);
 529                     e.next = dest[i];
 530                     dest[i] = e;
 531                 }
 532                 e = next;
 533             }
 534         }
 535     }
 536 
 537     /**
 538      * Copies all of the mappings from the specified map to this map.
 539      * These mappings will replace any mappings that this map had for any
 540      * of the keys currently in the specified map.
 541      *
 542      * @param m mappings to be stored in this map.
 543      * @throws  NullPointerException if the specified map is null.
 544      */
 545     public void putAll(Map<? extends K, ? extends V> m) {
 546         int numKeysToBeAdded = m.size();
 547         if (numKeysToBeAdded == 0)
 548             return;
 549 
 550         /*
 551          * Expand the map if the map if the number of mappings to be added
 552          * is greater than or equal to threshold.  This is conservative; the
 553          * obvious condition is (m.size() + size) >= threshold, but this
 554          * condition could result in a map with twice the appropriate capacity,
 555          * if the keys to be added overlap with the keys already in this map.
 556          * By using the conservative calculation, we subject ourself
 557          * to at most one extra resize.
 558          */
 559         if (numKeysToBeAdded > threshold) {
 560             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
 561             if (targetCapacity > MAXIMUM_CAPACITY)
 562                 targetCapacity = MAXIMUM_CAPACITY;
 563             int newCapacity = table.length;
 564             while (newCapacity < targetCapacity)
 565                 newCapacity <<= 1;
 566             if (newCapacity > table.length)
 567                 resize(newCapacity);
 568         }
 569 
 570         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
 571             put(e.getKey(), e.getValue());
 572     }
 573 
 574     /**
 575      * Removes the mapping for a key from this weak hash map if it is present.
 576      * More formally, if this map contains a mapping from key <tt>k</tt> to
 577      * value <tt>v</tt> such that <code>(key==null ?  k==null :
 578      * key.equals(k))</code>, that mapping is removed.  (The map can contain
 579      * at most one such mapping.)
 580      *
 581      * <p>Returns the value to which this map previously associated the key,
 582      * or <tt>null</tt> if the map contained no mapping for the key.  A
 583      * return value of <tt>null</tt> does not <i>necessarily</i> indicate
 584      * that the map contained no mapping for the key; it's also possible
 585      * that the map explicitly mapped the key to <tt>null</tt>.
 586      *
 587      * <p>The map will not contain a mapping for the specified key once the
 588      * call returns.
 589      *
 590      * @param key key whose mapping is to be removed from the map
 591      * @return the previous value associated with <tt>key</tt>, or
 592      *         <tt>null</tt> if there was no mapping for <tt>key</tt>
 593      */
 594     public V remove(Object key) {
 595         Object k = maskNull(key);
 596         int h = hash(k);
 597         Entry<K,V>[] tab = getTable();
 598         int i = indexFor(h, tab.length);
 599         Entry<K,V> prev = tab[i];
 600         Entry<K,V> e = prev;
 601 
 602         while (e != null) {
 603             Entry<K,V> next = e.next;
 604             if (h == e.hash && eq(k, e.get())) {
 605                 modCount++;
 606                 size--;
 607                 if (prev == e)
 608                     tab[i] = next;
 609                 else
 610                     prev.next = next;
 611                 return e.value;
 612             }
 613             prev = e;
 614             e = next;
 615         }
 616 
 617         return null;
 618     }
 619 
 620     /** Special version of remove needed by Entry set */
 621     boolean removeMapping(Object o) {
 622         if (!(o instanceof Map.Entry))
 623             return false;
 624         Entry<K,V>[] tab = getTable();
 625         Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
 626         Object k = maskNull(entry.getKey());
 627         int h = hash(k);
 628         int i = indexFor(h, tab.length);
 629         Entry<K,V> prev = tab[i];
 630         Entry<K,V> e = prev;
 631 
 632         while (e != null) {
 633             Entry<K,V> next = e.next;
 634             if (h == e.hash && e.equals(entry)) {
 635                 modCount++;
 636                 size--;
 637                 if (prev == e)
 638                     tab[i] = next;
 639                 else
 640                     prev.next = next;
 641                 return true;
 642             }
 643             prev = e;
 644             e = next;
 645         }
 646 
 647         return false;
 648     }
 649 
 650     /**
 651      * Removes all of the mappings from this map.
 652      * The map will be empty after this call returns.
 653      */
 654     public void clear() {
 655         // clear out ref queue. We don't need to expunge entries
 656         // since table is getting cleared.
 657         while (queue.poll() != null)
 658             ;
 659 
 660         modCount++;
 661         Arrays.fill(table, null);
 662         size = 0;
 663 
 664         // Allocation of array may have caused GC, which may have caused
 665         // additional entries to go stale.  Removing these entries from the
 666         // reference queue will make them eligible for reclamation.
 667         while (queue.poll() != null)
 668             ;
 669     }
 670 
 671     /**
 672      * Returns <tt>true</tt> if this map maps one or more keys to the
 673      * specified value.
 674      *
 675      * @param value value whose presence in this map is to be tested
 676      * @return <tt>true</tt> if this map maps one or more keys to the
 677      *         specified value
 678      */
 679     public boolean containsValue(Object value) {
 680         if (value==null)
 681             return containsNullValue();
 682 
 683         Entry<K,V>[] tab = getTable();
 684         for (int i = tab.length; i-- > 0;)
 685             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
 686                 if (value.equals(e.value))
 687                     return true;
 688         return false;
 689     }
 690 
 691     /**
 692      * Special-case code for containsValue with null argument
 693      */
 694     private boolean containsNullValue() {
 695         Entry<K,V>[] tab = getTable();
 696         for (int i = tab.length; i-- > 0;)
 697             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
 698                 if (e.value==null)
 699                     return true;
 700         return false;
 701     }
 702 
 703     /**
 704      * The entries in this hash table extend WeakReference, using its main ref
 705      * field as the key.
 706      */
 707     private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
 708         V value;
 709         final int hash;
 710         Entry<K,V> next;
 711 
 712         /**
 713          * Creates new entry.
 714          */
 715         Entry(Object key, V value,
 716               ReferenceQueue<Object> queue,
 717               int hash, Entry<K,V> next) {
 718             super(key, queue);
 719             this.value = value;
 720             this.hash  = hash;
 721             this.next  = next;
 722         }
 723 
 724         @SuppressWarnings("unchecked")
 725         public K getKey() {
 726             return (K) WeakHashMap.unmaskNull(get());
 727         }
 728 
 729         public V getValue() {
 730             return value;
 731         }
 732 
 733         public V setValue(V newValue) {
 734             V oldValue = value;
 735             value = newValue;
 736             return oldValue;
 737         }
 738 
 739         public boolean equals(Object o) {
 740             if (!(o instanceof Map.Entry))
 741                 return false;
 742             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
 743             K k1 = getKey();
 744             Object k2 = e.getKey();
 745             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
 746                 V v1 = getValue();
 747                 Object v2 = e.getValue();
 748                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
 749                     return true;
 750             }
 751             return false;
 752         }
 753 
 754         public int hashCode() {
 755             K k = getKey();
 756             V v = getValue();
 757             return ((k==null ? 0 : k.hashCode()) ^
 758                     (v==null ? 0 : v.hashCode()));
 759         }
 760 
 761         public String toString() {
 762             return getKey() + "=" + getValue();
 763         }
 764     }
 765 
 766     private abstract class HashIterator<T> implements Iterator<T> {
 767         private int index;
 768         private Entry<K,V> entry = null;
 769         private Entry<K,V> lastReturned = null;
 770         private int expectedModCount = modCount;
 771 
 772         /**
 773          * Strong reference needed to avoid disappearance of key
 774          * between hasNext and next
 775          */
 776         private Object nextKey = null;
 777 
 778         /**
 779          * Strong reference needed to avoid disappearance of key
 780          * between nextEntry() and any use of the entry
 781          */
 782         private Object currentKey = null;
 783 
 784         HashIterator() {
 785             index = isEmpty() ? 0 : table.length;
 786         }
 787 
 788         public boolean hasNext() {
 789             Entry<K,V>[] t = table;
 790 
 791             while (nextKey == null) {
 792                 Entry<K,V> e = entry;
 793                 int i = index;
 794                 while (e == null && i > 0)
 795                     e = t[--i];
 796                 entry = e;
 797                 index = i;
 798                 if (e == null) {
 799                     currentKey = null;
 800                     return false;
 801                 }
 802                 nextKey = e.get(); // hold on to key in strong ref
 803                 if (nextKey == null)
 804                     entry = entry.next;
 805             }
 806             return true;
 807         }
 808 
 809         /** The common parts of next() across different types of iterators */
 810         protected Entry<K,V> nextEntry() {
 811             if (modCount != expectedModCount)
 812                 throw new ConcurrentModificationException();
 813             if (nextKey == null && !hasNext())
 814                 throw new NoSuchElementException();
 815 
 816             lastReturned = entry;
 817             entry = entry.next;
 818             currentKey = nextKey;
 819             nextKey = null;
 820             return lastReturned;
 821         }
 822 
 823         public void remove() {
 824             if (lastReturned == null)
 825                 throw new IllegalStateException();
 826             if (modCount != expectedModCount)
 827                 throw new ConcurrentModificationException();
 828 
 829             WeakHashMap.this.remove(currentKey);
 830             expectedModCount = modCount;
 831             lastReturned = null;
 832             currentKey = null;
 833         }
 834 
 835     }
 836 
 837     private class ValueIterator extends HashIterator<V> {
 838         public V next() {
 839             return nextEntry().value;
 840         }
 841     }
 842 
 843     private class KeyIterator extends HashIterator<K> {
 844         public K next() {
 845             return nextEntry().getKey();
 846         }
 847     }
 848 
 849     private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
 850         public Map.Entry<K,V> next() {
 851             return nextEntry();
 852         }
 853     }
 854 
 855     // Views
 856 
 857     private transient Set<Map.Entry<K,V>> entrySet = null;
 858 
 859     /**
 860      * Returns a {@link Set} view of the keys contained in this map.
 861      * The set is backed by the map, so changes to the map are
 862      * reflected in the set, and vice-versa.  If the map is modified
 863      * while an iteration over the set is in progress (except through
 864      * the iterator's own <tt>remove</tt> operation), the results of
 865      * the iteration are undefined.  The set supports element removal,
 866      * which removes the corresponding mapping from the map, via the
 867      * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
 868      * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
 869      * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
 870      * operations.
 871      */
 872     public Set<K> keySet() {
 873         Set<K> ks = keySet;
 874         return (ks != null ? ks : (keySet = new KeySet()));
 875     }
 876 
 877     private class KeySet extends AbstractSet<K> {
 878         public Iterator<K> iterator() {
 879             return new KeyIterator();
 880         }
 881 
 882         public int size() {
 883             return WeakHashMap.this.size();
 884         }
 885 
 886         public boolean contains(Object o) {
 887             return containsKey(o);
 888         }
 889 
 890         public boolean remove(Object o) {
 891             if (containsKey(o)) {
 892                 WeakHashMap.this.remove(o);
 893                 return true;
 894             }
 895             else
 896                 return false;
 897         }
 898 
 899         public void clear() {
 900             WeakHashMap.this.clear();
 901         }
 902     }
 903 
 904     /**
 905      * Returns a {@link Collection} view of the values contained in this map.
 906      * The collection is backed by the map, so changes to the map are
 907      * reflected in the collection, and vice-versa.  If the map is
 908      * modified while an iteration over the collection is in progress
 909      * (except through the iterator's own <tt>remove</tt> operation),
 910      * the results of the iteration are undefined.  The collection
 911      * supports element removal, which removes the corresponding
 912      * mapping from the map, via the <tt>Iterator.remove</tt>,
 913      * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
 914      * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
 915      * support the <tt>add</tt> or <tt>addAll</tt> operations.
 916      */
 917     public Collection<V> values() {
 918         Collection<V> vs = values;
 919         return (vs != null) ? vs : (values = new Values());
 920     }
 921 
 922     private class Values extends AbstractCollection<V> {
 923         public Iterator<V> iterator() {
 924             return new ValueIterator();
 925         }
 926 
 927         public int size() {
 928             return WeakHashMap.this.size();
 929         }
 930 
 931         public boolean contains(Object o) {
 932             return containsValue(o);
 933         }
 934 
 935         public void clear() {
 936             WeakHashMap.this.clear();
 937         }
 938     }
 939 
 940     /**
 941      * Returns a {@link Set} view of the mappings contained in this map.
 942      * The set is backed by the map, so changes to the map are
 943      * reflected in the set, and vice-versa.  If the map is modified
 944      * while an iteration over the set is in progress (except through
 945      * the iterator's own <tt>remove</tt> operation, or through the
 946      * <tt>setValue</tt> operation on a map entry returned by the
 947      * iterator) the results of the iteration are undefined.  The set
 948      * supports element removal, which removes the corresponding
 949      * mapping from the map, via the <tt>Iterator.remove</tt>,
 950      * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
 951      * <tt>clear</tt> operations.  It does not support the
 952      * <tt>add</tt> or <tt>addAll</tt> operations.
 953      */
 954     public Set<Map.Entry<K,V>> entrySet() {
 955         Set<Map.Entry<K,V>> es = entrySet;
 956         return es != null ? es : (entrySet = new EntrySet());
 957     }
 958 
 959     private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
 960         public Iterator<Map.Entry<K,V>> iterator() {
 961             return new EntryIterator();
 962         }
 963 
 964         public boolean contains(Object o) {
 965             if (!(o instanceof Map.Entry))
 966                 return false;
 967             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
 968             Entry<K,V> candidate = getEntry(e.getKey());
 969             return candidate != null && candidate.equals(e);
 970         }
 971 
 972         public boolean remove(Object o) {
 973             return removeMapping(o);
 974         }
 975 
 976         public int size() {
 977             return WeakHashMap.this.size();
 978         }
 979 
 980         public void clear() {
 981             WeakHashMap.this.clear();
 982         }
 983 
 984         private List<Map.Entry<K,V>> deepCopy() {
 985             List<Map.Entry<K,V>> list = new ArrayList<>(size());
 986             for (Map.Entry<K,V> e : this)
 987                 list.add(new AbstractMap.SimpleEntry<>(e));
 988             return list;
 989         }
 990 
 991         public Object[] toArray() {
 992             return deepCopy().toArray();
 993         }
 994 
 995         public <T> T[] toArray(T[] a) {
 996             return deepCopy().toArray(a);
 997         }
 998     }
 999 }