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