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