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