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