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