1 /*
2  * Copyright (c) 1998, 2020, 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 
28 import java.lang.ref.WeakReference;
29 import java.lang.ref.ReferenceQueue;
30 import java.util.function.BiConsumer;
31 import java.util.function.BiFunction;
32 import java.util.function.Consumer;
33 
34 
35 /**
36  * Hash table based implementation of the {@code Map} interface, with
37  * <em>weak keys</em>.
38  * An entry in a {@code WeakHashMap} will automatically be removed when
39  * its key is no longer in ordinary use.  More precisely, the presence of a
40  * mapping for a given key will not prevent the key from being discarded by the
41  * garbage collector, that is, made finalizable, finalized, and then reclaimed.
42  * When a key has been discarded its entry is effectively removed from the map,
43  * so this class behaves somewhat differently from other {@code Map}
44  * implementations.
45  *
46  * <p> Both null values and the null key are supported. This class has
47  * performance characteristics similar to those of the {@code HashMap}
48  * class, and has the same efficiency parameters of <em>initial capacity</em>
49  * and <em>load factor</em>.
50  *
51  * <p> Like most collection classes, this class is not synchronized.
52  * A synchronized {@code WeakHashMap} may be constructed using the
53  * {@link Collections#synchronizedMap Collections.synchronizedMap}
54  * method.
55  *
56  * <p> This class is intended primarily for use with key objects whose
57  * {@code equals} methods test for object identity using the
58  * {@code ==} operator.  Once such a key is discarded it can never be
59  * recreated, so it is impossible to do a lookup of that key in a
60  * {@code WeakHashMap} at some later time and be surprised that its entry
61  * has been removed.  This class will work perfectly well with key objects
62  * whose {@code equals} methods are not based upon object identity, such
63  * as {@code String} instances.  With such recreatable key objects,
64  * however, the automatic removal of {@code WeakHashMap} entries whose
65  * keys have been discarded may prove to be confusing.
66  *
67  * <p> The behavior of the {@code WeakHashMap} class depends in part upon
68  * the actions of the garbage collector, so several familiar (though not
69  * required) {@code Map} invariants do not hold for this class.  Because
70  * the garbage collector may discard keys at any time, a
71  * {@code WeakHashMap} may behave as though an unknown thread is silently
72  * removing entries.  In particular, even if you synchronize on a
73  * {@code WeakHashMap} instance and invoke none of its mutator methods, it
74  * is possible for the {@code size} method to return smaller values over
75  * time, for the {@code isEmpty} method to return {@code false} and
76  * then {@code true}, for the {@code containsKey} method to return
77  * {@code true} and later {@code false} for a given key, for the
78  * {@code get} method to return a value for a given key but later return
79  * {@code null}, for the {@code put} method to return
80  * {@code null} and the {@code remove} method to return
81  * {@code false} for a key that previously appeared to be in the map, and
82  * for successive examinations of the key set, the value collection, and
83  * the entry set to yield successively smaller numbers of elements.
84  *
85  * <p> Each key object in a {@code WeakHashMap} is stored indirectly as
86  * the referent of a weak reference.  Therefore a key will automatically be
87  * removed only after the weak references to it, both inside and outside of the
88  * map, have been cleared by the garbage collector.
89  *
90  * <p> <strong>Implementation note:</strong> The value objects in a
91  * {@code WeakHashMap} are held by ordinary strong references.  Thus care
92  * should be taken to ensure that value objects do not strongly refer to their
93  * own keys, either directly or indirectly, since that will prevent the keys
94  * from being discarded.  Note that a value object may refer indirectly to its
95  * key via the {@code WeakHashMap} itself; that is, a value object may
96  * strongly refer to some other key object whose associated value object, in
97  * turn, strongly refers to the key of the first value object.  If the values
98  * in the map do not rely on the map holding strong references to them, one way
99  * to deal with this is to wrap values themselves within
100  * {@code WeakReferences} before
101  * inserting, as in: {@code m.put(key, new WeakReference(value))},
102  * and then unwrapping upon each {@code get}.
103  *
104  * <p>The iterators returned by the {@code iterator} method of the collections
105  * returned by all of this class's "collection view methods" are
106  * <i>fail-fast</i>: if the map is structurally modified at any time after the
107  * iterator is created, in any way except through the iterator's own
108  * {@code remove} method, the iterator will throw a {@link
109  * ConcurrentModificationException}.  Thus, in the face of concurrent
110  * modification, the iterator fails quickly and cleanly, rather than risking
111  * arbitrary, non-deterministic behavior at an undetermined time in the future.
112  *
113  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
114  * as it is, generally speaking, impossible to make any hard guarantees in the
115  * presence of unsynchronized concurrent modification.  Fail-fast iterators
116  * throw {@code ConcurrentModificationException} on a best-effort basis.
117  * Therefore, it would be wrong to write a program that depended on this
118  * exception for its correctness:  <i>the fail-fast behavior of iterators
119  * should be used only to detect bugs.</i>
120  *
121  * <p>This class is a member of the
122  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
123  * Java Collections Framework</a>.
124  *
125  * @param <K> the type of keys maintained by this map
126  * @param <V> the type of mapped values
127  *
128  * @author      Doug Lea
129  * @author      Josh Bloch
130  * @author      Mark Reinhold
131  * @since       1.2
132  * @see         java.util.HashMap
133  * @see         java.lang.ref.WeakReference
134  */
135 public class WeakHashMap<K,V>
136     extends AbstractMap<K,V>
137     implements Map<K,V> {
138 
139     /**
140      * The default initial capacity -- MUST be a power of two.
141      */
142     private static final int DEFAULT_INITIAL_CAPACITY = 16;
143 
144     /**
145      * The maximum capacity, used if a higher value is implicitly specified
146      * by either of the constructors with arguments.
147      * MUST be a power of two <= 1<<30.
148      */
149     private static final int MAXIMUM_CAPACITY = 1 << 30;
150 
151     /**
152      * The load factor used when none specified in constructor.
153      */
154     private static final float DEFAULT_LOAD_FACTOR = 0.75f;
155 
156     /**
157      * The table, resized as necessary. Length MUST Always be a power of two.
158      */
159     Entry<K,V>[] table;
160 
161     /**
162      * The number of key-value mappings contained in this weak hash map.
163      */
164     private int size;
165 
166     /**
167      * The next size value at which to resize (capacity * load factor).
168      */
169     private int threshold;
170 
171     /**
172      * The load factor for the hash table.
173      */
174     private final float loadFactor;
175 
176     /**
177      * Reference queue for cleared WeakEntries
178      */
179     private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
180 
181     /**
182      * The number of times this WeakHashMap has been structurally modified.
183      * Structural modifications are those that change the number of
184      * mappings in the map or otherwise modify its internal structure
185      * (e.g., rehash).  This field is used to make iterators on
186      * Collection-views of the map fail-fast.
187      *
188      * @see ConcurrentModificationException
189      */
190     int modCount;
191 
192     @SuppressWarnings("unchecked")
newTable(int n)193     private Entry<K,V>[] newTable(int n) {
194         return (Entry<K,V>[]) new Entry<?,?>[n];
195     }
196 
197     /**
198      * Constructs a new, empty {@code WeakHashMap} with the given initial
199      * capacity and the given load factor.
200      *
201      * @param  initialCapacity The initial capacity of the {@code WeakHashMap}
202      * @param  loadFactor      The load factor of the {@code WeakHashMap}
203      * @throws IllegalArgumentException if the initial capacity is negative,
204      *         or if the load factor is nonpositive.
205      */
WeakHashMap(int initialCapacity, float loadFactor)206     public WeakHashMap(int initialCapacity, float loadFactor) {
207         if (initialCapacity < 0)
208             throw new IllegalArgumentException("Illegal Initial Capacity: "+
209                                                initialCapacity);
210         if (initialCapacity > MAXIMUM_CAPACITY)
211             initialCapacity = MAXIMUM_CAPACITY;
212 
213         if (loadFactor <= 0 || Float.isNaN(loadFactor))
214             throw new IllegalArgumentException("Illegal Load factor: "+
215                                                loadFactor);
216         int capacity = 1;
217         while (capacity < initialCapacity)
218             capacity <<= 1;
219         table = newTable(capacity);
220         this.loadFactor = loadFactor;
221         threshold = (int)(capacity * loadFactor);
222     }
223 
224     /**
225      * Constructs a new, empty {@code WeakHashMap} with the given initial
226      * capacity and the default load factor (0.75).
227      *
228      * @param  initialCapacity The initial capacity of the {@code WeakHashMap}
229      * @throws IllegalArgumentException if the initial capacity is negative
230      */
WeakHashMap(int initialCapacity)231     public WeakHashMap(int initialCapacity) {
232         this(initialCapacity, DEFAULT_LOAD_FACTOR);
233     }
234 
235     /**
236      * Constructs a new, empty {@code WeakHashMap} with the default initial
237      * capacity (16) and load factor (0.75).
238      */
WeakHashMap()239     public WeakHashMap() {
240         this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
241     }
242 
243     /**
244      * Constructs a new {@code WeakHashMap} with the same mappings as the
245      * specified map.  The {@code WeakHashMap} is created with the default
246      * load factor (0.75) and an initial capacity sufficient to hold the
247      * mappings in the specified map.
248      *
249      * @param   m the map whose mappings are to be placed in this map
250      * @throws  NullPointerException if the specified map is null
251      * @since   1.3
252      */
WeakHashMap(Map<? extends K, ? extends V> m)253     public WeakHashMap(Map<? extends K, ? extends V> m) {
254         this(Math.max((int) ((float)m.size() / DEFAULT_LOAD_FACTOR + 1.0F),
255                 DEFAULT_INITIAL_CAPACITY),
256              DEFAULT_LOAD_FACTOR);
257         putAll(m);
258     }
259 
260     // internal utilities
261 
262     /**
263      * Value representing null keys inside tables.
264      */
265     private static final Object NULL_KEY = new Object();
266 
267     /**
268      * Use NULL_KEY for key if it is null.
269      */
maskNull(Object key)270     private static Object maskNull(Object key) {
271         return (key == null) ? NULL_KEY : key;
272     }
273 
274     /**
275      * Returns internal representation of null key back to caller as null.
276      */
unmaskNull(Object key)277     static Object unmaskNull(Object key) {
278         return (key == NULL_KEY) ? null : key;
279     }
280 
281     /**
282      * Checks for equality of non-null reference x and possibly-null y.  By
283      * default uses Object.equals.
284      */
matchesKey(Entry<K,V> e, Object key)285     private boolean matchesKey(Entry<K,V> e, Object key) {
286         // check if the given entry refers to the given key without
287         // keeping a strong reference to the entry's referent
288         if (e.refersTo(key)) return true;
289 
290         // then check for equality if the referent is not cleared
291         Object k = e.get();
292         return k != null && key.equals(k);
293     }
294 
295     /**
296      * Retrieve object hash code and applies a supplemental hash function to the
297      * result hash, which defends against poor quality hash functions.  This is
298      * critical because HashMap uses power-of-two length hash tables, that
299      * otherwise encounter collisions for hashCodes that do not differ
300      * in lower bits.
301      */
hash(Object k)302     final int hash(Object k) {
303         int h = k.hashCode();
304 
305         // This function ensures that hashCodes that differ only by
306         // constant multiples at each bit position have a bounded
307         // number of collisions (approximately 8 at default load factor).
308         h ^= (h >>> 20) ^ (h >>> 12);
309         return h ^ (h >>> 7) ^ (h >>> 4);
310     }
311 
312     /**
313      * Returns index for hash code h.
314      */
indexFor(int h, int length)315     private static int indexFor(int h, int length) {
316         return h & (length-1);
317     }
318 
319     /**
320      * Expunges stale entries from the table.
321      */
expungeStaleEntries()322     private void expungeStaleEntries() {
323         for (Object x; (x = queue.poll()) != null; ) {
324             synchronized (queue) {
325                 @SuppressWarnings("unchecked")
326                     Entry<K,V> e = (Entry<K,V>) x;
327                 int i = indexFor(e.hash, table.length);
328 
329                 Entry<K,V> prev = table[i];
330                 Entry<K,V> p = prev;
331                 while (p != null) {
332                     Entry<K,V> next = p.next;
333                     if (p == e) {
334                         if (prev == e)
335                             table[i] = next;
336                         else
337                             prev.next = next;
338                         // Must not null out e.next;
339                         // stale entries may be in use by a HashIterator
340                         e.value = null; // Help GC
341                         size--;
342                         break;
343                     }
344                     prev = p;
345                     p = next;
346                 }
347             }
348         }
349     }
350 
351     /**
352      * Returns the table after first expunging stale entries.
353      */
getTable()354     private Entry<K,V>[] getTable() {
355         expungeStaleEntries();
356         return table;
357     }
358 
359     /**
360      * Returns the number of key-value mappings in this map.
361      * This result is a snapshot, and may not reflect unprocessed
362      * entries that will be removed before next attempted access
363      * because they are no longer referenced.
364      */
size()365     public int size() {
366         if (size == 0)
367             return 0;
368         expungeStaleEntries();
369         return size;
370     }
371 
372     /**
373      * Returns {@code true} if this map contains no key-value mappings.
374      * This result is a snapshot, and may not reflect unprocessed
375      * entries that will be removed before next attempted access
376      * because they are no longer referenced.
377      */
isEmpty()378     public boolean isEmpty() {
379         return size() == 0;
380     }
381 
382     /**
383      * Returns the value to which the specified key is mapped,
384      * or {@code null} if this map contains no mapping for the key.
385      *
386      * <p>More formally, if this map contains a mapping from a key
387      * {@code k} to a value {@code v} such that
388      * {@code Objects.equals(key, k)},
389      * then this method returns {@code v}; otherwise
390      * it returns {@code null}.  (There can be at most one such mapping.)
391      *
392      * <p>A return value of {@code null} does not <i>necessarily</i>
393      * indicate that the map contains no mapping for the key; it's also
394      * possible that the map explicitly maps the key to {@code null}.
395      * The {@link #containsKey containsKey} operation may be used to
396      * distinguish these two cases.
397      *
398      * @see #put(Object, Object)
399      */
get(Object key)400     public V get(Object key) {
401         Object k = maskNull(key);
402         int h = hash(k);
403         Entry<K,V>[] tab = getTable();
404         int index = indexFor(h, tab.length);
405         Entry<K,V> e = tab[index];
406         while (e != null) {
407             if (e.hash == h && matchesKey(e, k))
408                 return e.value;
409             e = e.next;
410         }
411         return null;
412     }
413 
414     /**
415      * Returns {@code true} if this map contains a mapping for the
416      * specified key.
417      *
418      * @param  key   The key whose presence in this map is to be tested
419      * @return {@code true} if there is a mapping for {@code key};
420      *         {@code false} otherwise
421      */
containsKey(Object key)422     public boolean containsKey(Object key) {
423         return getEntry(key) != null;
424     }
425 
426     /**
427      * Returns the entry associated with the specified key in this map.
428      * Returns null if the map contains no mapping for this key.
429      */
getEntry(Object key)430     Entry<K,V> getEntry(Object key) {
431         Object k = maskNull(key);
432         int h = hash(k);
433         Entry<K,V>[] tab = getTable();
434         int index = indexFor(h, tab.length);
435         Entry<K,V> e = tab[index];
436         while (e != null && !(e.hash == h && matchesKey(e, k)))
437             e = e.next;
438         return e;
439     }
440 
441     /**
442      * Associates the specified value with the specified key in this map.
443      * If the map previously contained a mapping for this key, the old
444      * value is replaced.
445      *
446      * @param key key with which the specified value is to be associated.
447      * @param value value to be associated with the specified key.
448      * @return the previous value associated with {@code key}, or
449      *         {@code null} if there was no mapping for {@code key}.
450      *         (A {@code null} return can also indicate that the map
451      *         previously associated {@code null} with {@code key}.)
452      */
put(K key, V value)453     public V put(K key, V value) {
454         Object k = maskNull(key);
455         int h = hash(k);
456         Entry<K,V>[] tab = getTable();
457         int i = indexFor(h, tab.length);
458 
459         for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
460             if (h == e.hash && matchesKey(e, k)) {
461                 V oldValue = e.value;
462                 if (value != oldValue)
463                     e.value = value;
464                 return oldValue;
465             }
466         }
467 
468         modCount++;
469         Entry<K,V> e = tab[i];
470         tab[i] = new Entry<>(k, value, queue, h, e);
471         if (++size >= threshold)
472             resize(tab.length * 2);
473         return null;
474     }
475 
476     /**
477      * Rehashes the contents of this map into a new array with a
478      * larger capacity.  This method is called automatically when the
479      * number of keys in this map reaches its threshold.
480      *
481      * If current capacity is MAXIMUM_CAPACITY, this method does not
482      * resize the map, but sets threshold to Integer.MAX_VALUE.
483      * This has the effect of preventing future calls.
484      *
485      * @param newCapacity the new capacity, MUST be a power of two;
486      *        must be greater than current capacity unless current
487      *        capacity is MAXIMUM_CAPACITY (in which case value
488      *        is irrelevant).
489      */
resize(int newCapacity)490     void resize(int newCapacity) {
491         Entry<K,V>[] oldTable = getTable();
492         int oldCapacity = oldTable.length;
493         if (oldCapacity == MAXIMUM_CAPACITY) {
494             threshold = Integer.MAX_VALUE;
495             return;
496         }
497 
498         Entry<K,V>[] newTable = newTable(newCapacity);
499         transfer(oldTable, newTable);
500         table = newTable;
501 
502         /*
503          * If ignoring null elements and processing ref queue caused massive
504          * shrinkage, then restore old table.  This should be rare, but avoids
505          * unbounded expansion of garbage-filled tables.
506          */
507         if (size >= threshold / 2) {
508             threshold = (int)(newCapacity * loadFactor);
509         } else {
510             expungeStaleEntries();
511             transfer(newTable, oldTable);
512             table = oldTable;
513         }
514     }
515 
516     /** Transfers all entries from src to dest tables */
transfer(Entry<K,V>[] src, Entry<K,V>[] dest)517     private void transfer(Entry<K,V>[] src, Entry<K,V>[] dest) {
518         for (int j = 0; j < src.length; ++j) {
519             Entry<K,V> e = src[j];
520             src[j] = null;
521             while (e != null) {
522                 Entry<K,V> next = e.next;
523                 if (e.refersTo(null)) {
524                     e.next = null;  // Help GC
525                     e.value = null; //  "   "
526                     size--;
527                 } else {
528                     int i = indexFor(e.hash, dest.length);
529                     e.next = dest[i];
530                     dest[i] = e;
531                 }
532                 e = next;
533             }
534         }
535     }
536 
537     /**
538      * Copies all of the mappings from the specified map to this map.
539      * These mappings will replace any mappings that this map had for any
540      * of the keys currently in the specified map.
541      *
542      * @param m mappings to be stored in this map.
543      * @throws  NullPointerException if the specified map is null.
544      */
putAll(Map<? extends K, ? extends V> m)545     public void putAll(Map<? extends K, ? extends V> m) {
546         int numKeysToBeAdded = m.size();
547         if (numKeysToBeAdded == 0)
548             return;
549 
550         /*
551          * Expand the map if the map if the number of mappings to be added
552          * is greater than or equal to threshold.  This is conservative; the
553          * obvious condition is (m.size() + size) >= threshold, but this
554          * condition could result in a map with twice the appropriate capacity,
555          * if the keys to be added overlap with the keys already in this map.
556          * By using the conservative calculation, we subject ourself
557          * to at most one extra resize.
558          */
559         if (numKeysToBeAdded > threshold) {
560             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
561             if (targetCapacity > MAXIMUM_CAPACITY)
562                 targetCapacity = MAXIMUM_CAPACITY;
563             int newCapacity = table.length;
564             while (newCapacity < targetCapacity)
565                 newCapacity <<= 1;
566             if (newCapacity > table.length)
567                 resize(newCapacity);
568         }
569 
570         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
571             put(e.getKey(), e.getValue());
572     }
573 
574     /**
575      * Removes the mapping for a key from this weak hash map if it is present.
576      * More formally, if this map contains a mapping from key {@code k} to
577      * value {@code v} such that <code>(key==null ?  k==null :
578      * key.equals(k))</code>, that mapping is removed.  (The map can contain
579      * at most one such mapping.)
580      *
581      * <p>Returns the value to which this map previously associated the key,
582      * or {@code null} if the map contained no mapping for the key.  A
583      * return value of {@code null} does not <i>necessarily</i> indicate
584      * that the map contained no mapping for the key; it's also possible
585      * that the map explicitly mapped the key to {@code null}.
586      *
587      * <p>The map will not contain a mapping for the specified key once the
588      * call returns.
589      *
590      * @param key key whose mapping is to be removed from the map
591      * @return the previous value associated with {@code key}, or
592      *         {@code null} if there was no mapping for {@code key}
593      */
remove(Object key)594     public V remove(Object key) {
595         Object k = maskNull(key);
596         int h = hash(k);
597         Entry<K,V>[] tab = getTable();
598         int i = indexFor(h, tab.length);
599         Entry<K,V> prev = tab[i];
600         Entry<K,V> e = prev;
601 
602         while (e != null) {
603             Entry<K,V> next = e.next;
604             if (h == e.hash && matchesKey(e, k)) {
605                 modCount++;
606                 size--;
607                 if (prev == e)
608                     tab[i] = next;
609                 else
610                     prev.next = next;
611                 return e.value;
612             }
613             prev = e;
614             e = next;
615         }
616 
617         return null;
618     }
619 
620     /** Special version of remove needed by Entry set */
removeMapping(Object o)621     boolean removeMapping(Object o) {
622         if (!(o instanceof Map.Entry<?, ?> entry))
623             return false;
624         Entry<K,V>[] tab = getTable();
625         Object k = maskNull(entry.getKey());
626         int h = hash(k);
627         int i = indexFor(h, tab.length);
628         Entry<K,V> prev = tab[i];
629         Entry<K,V> e = prev;
630 
631         while (e != null) {
632             Entry<K,V> next = e.next;
633             if (h == e.hash && e.equals(entry)) {
634                 modCount++;
635                 size--;
636                 if (prev == e)
637                     tab[i] = next;
638                 else
639                     prev.next = next;
640                 return true;
641             }
642             prev = e;
643             e = next;
644         }
645 
646         return false;
647     }
648 
649     /**
650      * Removes all of the mappings from this map.
651      * The map will be empty after this call returns.
652      */
clear()653     public void clear() {
654         // clear out ref queue. We don't need to expunge entries
655         // since table is getting cleared.
656         while (queue.poll() != null)
657             ;
658 
659         modCount++;
660         Arrays.fill(table, null);
661         size = 0;
662 
663         // Allocation of array may have caused GC, which may have caused
664         // additional entries to go stale.  Removing these entries from the
665         // reference queue will make them eligible for reclamation.
666         while (queue.poll() != null)
667             ;
668     }
669 
670     /**
671      * Returns {@code true} if this map maps one or more keys to the
672      * specified value.
673      *
674      * @param value value whose presence in this map is to be tested
675      * @return {@code true} if this map maps one or more keys to the
676      *         specified value
677      */
containsValue(Object value)678     public boolean containsValue(Object value) {
679         if (value==null)
680             return containsNullValue();
681 
682         Entry<K,V>[] tab = getTable();
683         for (int i = tab.length; i-- > 0;)
684             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
685                 if (value.equals(e.value))
686                     return true;
687         return false;
688     }
689 
690     /**
691      * Special-case code for containsValue with null argument
692      */
containsNullValue()693     private boolean containsNullValue() {
694         Entry<K,V>[] tab = getTable();
695         for (int i = tab.length; i-- > 0;)
696             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
697                 if (e.value==null)
698                     return true;
699         return false;
700     }
701 
702     /**
703      * The entries in this hash table extend WeakReference, using its main ref
704      * field as the key.
705      */
706     private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
707         V value;
708         final int hash;
709         Entry<K,V> next;
710 
711         /**
712          * Creates new entry.
713          */
Entry(Object key, V value, ReferenceQueue<Object> queue, int hash, Entry<K,V> next)714         Entry(Object key, V value,
715               ReferenceQueue<Object> queue,
716               int hash, Entry<K,V> next) {
717             super(key, queue);
718             this.value = value;
719             this.hash  = hash;
720             this.next  = next;
721         }
722 
723         @SuppressWarnings("unchecked")
getKey()724         public K getKey() {
725             return (K) WeakHashMap.unmaskNull(get());
726         }
727 
getValue()728         public V getValue() {
729             return value;
730         }
731 
setValue(V newValue)732         public V setValue(V newValue) {
733             V oldValue = value;
734             value = newValue;
735             return oldValue;
736         }
737 
equals(Object o)738         public boolean equals(Object o) {
739             if (!(o instanceof Map.Entry<?, ?> e))
740                 return false;
741             K k1 = getKey();
742             Object k2 = e.getKey();
743             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
744                 V v1 = getValue();
745                 Object v2 = e.getValue();
746                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
747                     return true;
748             }
749             return false;
750         }
751 
hashCode()752         public int hashCode() {
753             K k = getKey();
754             V v = getValue();
755             return Objects.hashCode(k) ^ Objects.hashCode(v);
756         }
757 
toString()758         public String toString() {
759             return getKey() + "=" + getValue();
760         }
761     }
762 
763     private abstract class HashIterator<T> implements Iterator<T> {
764         private int index;
765         private Entry<K,V> entry;
766         private Entry<K,V> lastReturned;
767         private int expectedModCount = modCount;
768 
769         /**
770          * Strong reference needed to avoid disappearance of key
771          * between hasNext and next
772          */
773         private Object nextKey;
774 
775         /**
776          * Strong reference needed to avoid disappearance of key
777          * between nextEntry() and any use of the entry
778          */
779         private Object currentKey;
780 
HashIterator()781         HashIterator() {
782             index = isEmpty() ? 0 : table.length;
783         }
784 
hasNext()785         public boolean hasNext() {
786             Entry<K,V>[] t = table;
787 
788             while (nextKey == null) {
789                 Entry<K,V> e = entry;
790                 int i = index;
791                 while (e == null && i > 0)
792                     e = t[--i];
793                 entry = e;
794                 index = i;
795                 if (e == null) {
796                     currentKey = null;
797                     return false;
798                 }
799                 nextKey = e.get(); // hold on to key in strong ref
800                 if (nextKey == null)
801                     entry = entry.next;
802             }
803             return true;
804         }
805 
806         /** The common parts of next() across different types of iterators */
nextEntry()807         protected Entry<K,V> nextEntry() {
808             if (modCount != expectedModCount)
809                 throw new ConcurrentModificationException();
810             if (nextKey == null && !hasNext())
811                 throw new NoSuchElementException();
812 
813             lastReturned = entry;
814             entry = entry.next;
815             currentKey = nextKey;
816             nextKey = null;
817             return lastReturned;
818         }
819 
remove()820         public void remove() {
821             if (lastReturned == null)
822                 throw new IllegalStateException();
823             if (modCount != expectedModCount)
824                 throw new ConcurrentModificationException();
825 
826             WeakHashMap.this.remove(currentKey);
827             expectedModCount = modCount;
828             lastReturned = null;
829             currentKey = null;
830         }
831 
832     }
833 
834     private class ValueIterator extends HashIterator<V> {
next()835         public V next() {
836             return nextEntry().value;
837         }
838     }
839 
840     private class KeyIterator extends HashIterator<K> {
next()841         public K next() {
842             return nextEntry().getKey();
843         }
844     }
845 
846     private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
next()847         public Map.Entry<K,V> next() {
848             return nextEntry();
849         }
850     }
851 
852     // Views
853 
854     private transient Set<Map.Entry<K,V>> entrySet;
855 
856     /**
857      * Returns a {@link Set} view of the keys contained in this map.
858      * The set is backed by the map, so changes to the map are
859      * reflected in the set, and vice-versa.  If the map is modified
860      * while an iteration over the set is in progress (except through
861      * the iterator's own {@code remove} operation), the results of
862      * the iteration are undefined.  The set supports element removal,
863      * which removes the corresponding mapping from the map, via the
864      * {@code Iterator.remove}, {@code Set.remove},
865      * {@code removeAll}, {@code retainAll}, and {@code clear}
866      * operations.  It does not support the {@code add} or {@code addAll}
867      * operations.
868      */
keySet()869     public Set<K> keySet() {
870         Set<K> ks = keySet;
871         if (ks == null) {
872             ks = new KeySet();
873             keySet = ks;
874         }
875         return ks;
876     }
877 
878     private class KeySet extends AbstractSet<K> {
iterator()879         public Iterator<K> iterator() {
880             return new KeyIterator();
881         }
882 
size()883         public int size() {
884             return WeakHashMap.this.size();
885         }
886 
contains(Object o)887         public boolean contains(Object o) {
888             return containsKey(o);
889         }
890 
remove(Object o)891         public boolean remove(Object o) {
892             if (containsKey(o)) {
893                 WeakHashMap.this.remove(o);
894                 return true;
895             }
896             else
897                 return false;
898         }
899 
clear()900         public void clear() {
901             WeakHashMap.this.clear();
902         }
903 
spliterator()904         public Spliterator<K> spliterator() {
905             return new KeySpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
906         }
907     }
908 
909     /**
910      * Returns a {@link Collection} view of the values contained in this map.
911      * The collection is backed by the map, so changes to the map are
912      * reflected in the collection, and vice-versa.  If the map is
913      * modified while an iteration over the collection is in progress
914      * (except through the iterator's own {@code remove} operation),
915      * the results of the iteration are undefined.  The collection
916      * supports element removal, which removes the corresponding
917      * mapping from the map, via the {@code Iterator.remove},
918      * {@code Collection.remove}, {@code removeAll},
919      * {@code retainAll} and {@code clear} operations.  It does not
920      * support the {@code add} or {@code addAll} operations.
921      */
values()922     public Collection<V> values() {
923         Collection<V> vs = values;
924         if (vs == null) {
925             vs = new Values();
926             values = vs;
927         }
928         return vs;
929     }
930 
931     private class Values extends AbstractCollection<V> {
iterator()932         public Iterator<V> iterator() {
933             return new ValueIterator();
934         }
935 
size()936         public int size() {
937             return WeakHashMap.this.size();
938         }
939 
contains(Object o)940         public boolean contains(Object o) {
941             return containsValue(o);
942         }
943 
clear()944         public void clear() {
945             WeakHashMap.this.clear();
946         }
947 
spliterator()948         public Spliterator<V> spliterator() {
949             return new ValueSpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
950         }
951     }
952 
953     /**
954      * Returns a {@link Set} view of the mappings contained in this map.
955      * The set is backed by the map, so changes to the map are
956      * reflected in the set, and vice-versa.  If the map is modified
957      * while an iteration over the set is in progress (except through
958      * the iterator's own {@code remove} operation, or through the
959      * {@code setValue} operation on a map entry returned by the
960      * iterator) the results of the iteration are undefined.  The set
961      * supports element removal, which removes the corresponding
962      * mapping from the map, via the {@code Iterator.remove},
963      * {@code Set.remove}, {@code removeAll}, {@code retainAll} and
964      * {@code clear} operations.  It does not support the
965      * {@code add} or {@code addAll} operations.
966      */
entrySet()967     public Set<Map.Entry<K,V>> entrySet() {
968         Set<Map.Entry<K,V>> es = entrySet;
969         return es != null ? es : (entrySet = new EntrySet());
970     }
971 
972     private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
iterator()973         public Iterator<Map.Entry<K,V>> iterator() {
974             return new EntryIterator();
975         }
976 
contains(Object o)977         public boolean contains(Object o) {
978             return o instanceof Map.Entry<?, ?> e
979                     && getEntry(e.getKey()) != null
980                     && getEntry(e.getKey()).equals(e);
981         }
982 
remove(Object o)983         public boolean remove(Object o) {
984             return removeMapping(o);
985         }
986 
size()987         public int size() {
988             return WeakHashMap.this.size();
989         }
990 
clear()991         public void clear() {
992             WeakHashMap.this.clear();
993         }
994 
deepCopy()995         private List<Map.Entry<K,V>> deepCopy() {
996             List<Map.Entry<K,V>> list = new ArrayList<>(size());
997             for (Map.Entry<K,V> e : this)
998                 list.add(new AbstractMap.SimpleEntry<>(e));
999             return list;
1000         }
1001 
toArray()1002         public Object[] toArray() {
1003             return deepCopy().toArray();
1004         }
1005 
toArray(T[] a)1006         public <T> T[] toArray(T[] a) {
1007             return deepCopy().toArray(a);
1008         }
1009 
spliterator()1010         public Spliterator<Map.Entry<K,V>> spliterator() {
1011             return new EntrySpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
1012         }
1013     }
1014 
1015     @SuppressWarnings("unchecked")
1016     @Override
forEach(BiConsumer<? super K, ? super V> action)1017     public void forEach(BiConsumer<? super K, ? super V> action) {
1018         Objects.requireNonNull(action);
1019         int expectedModCount = modCount;
1020 
1021         Entry<K, V>[] tab = getTable();
1022         for (Entry<K, V> entry : tab) {
1023             while (entry != null) {
1024                 Object key = entry.get();
1025                 if (key != null) {
1026                     action.accept((K)WeakHashMap.unmaskNull(key), entry.value);
1027                 }
1028                 entry = entry.next;
1029 
1030                 if (expectedModCount != modCount) {
1031                     throw new ConcurrentModificationException();
1032                 }
1033             }
1034         }
1035     }
1036 
1037     @SuppressWarnings("unchecked")
1038     @Override
replaceAll(BiFunction<? super K, ? super V, ? extends V> function)1039     public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1040         Objects.requireNonNull(function);
1041         int expectedModCount = modCount;
1042 
1043         Entry<K, V>[] tab = getTable();;
1044         for (Entry<K, V> entry : tab) {
1045             while (entry != null) {
1046                 Object key = entry.get();
1047                 if (key != null) {
1048                     entry.value = function.apply((K)WeakHashMap.unmaskNull(key), entry.value);
1049                 }
1050                 entry = entry.next;
1051 
1052                 if (expectedModCount != modCount) {
1053                     throw new ConcurrentModificationException();
1054                 }
1055             }
1056         }
1057     }
1058 
1059     /**
1060      * Similar form as other hash Spliterators, but skips dead
1061      * elements.
1062      */
1063     static class WeakHashMapSpliterator<K,V> {
1064         final WeakHashMap<K,V> map;
1065         WeakHashMap.Entry<K,V> current; // current node
1066         int index;             // current index, modified on advance/split
1067         int fence;             // -1 until first use; then one past last index
1068         int est;               // size estimate
1069         int expectedModCount;  // for comodification checks
1070 
WeakHashMapSpliterator(WeakHashMap<K,V> m, int origin, int fence, int est, int expectedModCount)1071         WeakHashMapSpliterator(WeakHashMap<K,V> m, int origin,
1072                                int fence, int est,
1073                                int expectedModCount) {
1074             this.map = m;
1075             this.index = origin;
1076             this.fence = fence;
1077             this.est = est;
1078             this.expectedModCount = expectedModCount;
1079         }
1080 
getFence()1081         final int getFence() { // initialize fence and size on first use
1082             int hi;
1083             if ((hi = fence) < 0) {
1084                 WeakHashMap<K,V> m = map;
1085                 est = m.size();
1086                 expectedModCount = m.modCount;
1087                 hi = fence = m.table.length;
1088             }
1089             return hi;
1090         }
1091 
estimateSize()1092         public final long estimateSize() {
1093             getFence(); // force init
1094             return (long) est;
1095         }
1096     }
1097 
1098     static final class KeySpliterator<K,V>
1099         extends WeakHashMapSpliterator<K,V>
1100         implements Spliterator<K> {
KeySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est, int expectedModCount)1101         KeySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1102                        int expectedModCount) {
1103             super(m, origin, fence, est, expectedModCount);
1104         }
1105 
trySplit()1106         public KeySpliterator<K,V> trySplit() {
1107             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1108             return (lo >= mid) ? null :
1109                 new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
1110                                      expectedModCount);
1111         }
1112 
forEachRemaining(Consumer<? super K> action)1113         public void forEachRemaining(Consumer<? super K> action) {
1114             int i, hi, mc;
1115             if (action == null)
1116                 throw new NullPointerException();
1117             WeakHashMap<K,V> m = map;
1118             WeakHashMap.Entry<K,V>[] tab = m.table;
1119             if ((hi = fence) < 0) {
1120                 mc = expectedModCount = m.modCount;
1121                 hi = fence = tab.length;
1122             }
1123             else
1124                 mc = expectedModCount;
1125             if (tab.length >= hi && (i = index) >= 0 &&
1126                 (i < (index = hi) || current != null)) {
1127                 WeakHashMap.Entry<K,V> p = current;
1128                 current = null; // exhaust
1129                 do {
1130                     if (p == null)
1131                         p = tab[i++];
1132                     else {
1133                         Object x = p.get();
1134                         p = p.next;
1135                         if (x != null) {
1136                             @SuppressWarnings("unchecked") K k =
1137                                 (K) WeakHashMap.unmaskNull(x);
1138                             action.accept(k);
1139                         }
1140                     }
1141                 } while (p != null || i < hi);
1142             }
1143             if (m.modCount != mc)
1144                 throw new ConcurrentModificationException();
1145         }
1146 
tryAdvance(Consumer<? super K> action)1147         public boolean tryAdvance(Consumer<? super K> action) {
1148             int hi;
1149             if (action == null)
1150                 throw new NullPointerException();
1151             WeakHashMap.Entry<K,V>[] tab = map.table;
1152             if (tab.length >= (hi = getFence()) && index >= 0) {
1153                 while (current != null || index < hi) {
1154                     if (current == null)
1155                         current = tab[index++];
1156                     else {
1157                         Object x = current.get();
1158                         current = current.next;
1159                         if (x != null) {
1160                             @SuppressWarnings("unchecked") K k =
1161                                 (K) WeakHashMap.unmaskNull(x);
1162                             action.accept(k);
1163                             if (map.modCount != expectedModCount)
1164                                 throw new ConcurrentModificationException();
1165                             return true;
1166                         }
1167                     }
1168                 }
1169             }
1170             return false;
1171         }
1172 
characteristics()1173         public int characteristics() {
1174             return Spliterator.DISTINCT;
1175         }
1176     }
1177 
1178     static final class ValueSpliterator<K,V>
1179         extends WeakHashMapSpliterator<K,V>
1180         implements Spliterator<V> {
ValueSpliterator(WeakHashMap<K,V> m, int origin, int fence, int est, int expectedModCount)1181         ValueSpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1182                          int expectedModCount) {
1183             super(m, origin, fence, est, expectedModCount);
1184         }
1185 
trySplit()1186         public ValueSpliterator<K,V> trySplit() {
1187             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1188             return (lo >= mid) ? null :
1189                 new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
1190                                        expectedModCount);
1191         }
1192 
forEachRemaining(Consumer<? super V> action)1193         public void forEachRemaining(Consumer<? super V> action) {
1194             int i, hi, mc;
1195             if (action == null)
1196                 throw new NullPointerException();
1197             WeakHashMap<K,V> m = map;
1198             WeakHashMap.Entry<K,V>[] tab = m.table;
1199             if ((hi = fence) < 0) {
1200                 mc = expectedModCount = m.modCount;
1201                 hi = fence = tab.length;
1202             }
1203             else
1204                 mc = expectedModCount;
1205             if (tab.length >= hi && (i = index) >= 0 &&
1206                 (i < (index = hi) || current != null)) {
1207                 WeakHashMap.Entry<K,V> p = current;
1208                 current = null; // exhaust
1209                 do {
1210                     if (p == null)
1211                         p = tab[i++];
1212                     else {
1213                         Object x = p.get();
1214                         V v = p.value;
1215                         p = p.next;
1216                         if (x != null)
1217                             action.accept(v);
1218                     }
1219                 } while (p != null || i < hi);
1220             }
1221             if (m.modCount != mc)
1222                 throw new ConcurrentModificationException();
1223         }
1224 
tryAdvance(Consumer<? super V> action)1225         public boolean tryAdvance(Consumer<? super V> action) {
1226             int hi;
1227             if (action == null)
1228                 throw new NullPointerException();
1229             WeakHashMap.Entry<K,V>[] tab = map.table;
1230             if (tab.length >= (hi = getFence()) && index >= 0) {
1231                 while (current != null || index < hi) {
1232                     if (current == null)
1233                         current = tab[index++];
1234                     else {
1235                         Object x = current.get();
1236                         V v = current.value;
1237                         current = current.next;
1238                         if (x != null) {
1239                             action.accept(v);
1240                             if (map.modCount != expectedModCount)
1241                                 throw new ConcurrentModificationException();
1242                             return true;
1243                         }
1244                     }
1245                 }
1246             }
1247             return false;
1248         }
1249 
characteristics()1250         public int characteristics() {
1251             return 0;
1252         }
1253     }
1254 
1255     static final class EntrySpliterator<K,V>
1256         extends WeakHashMapSpliterator<K,V>
1257         implements Spliterator<Map.Entry<K,V>> {
EntrySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est, int expectedModCount)1258         EntrySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1259                        int expectedModCount) {
1260             super(m, origin, fence, est, expectedModCount);
1261         }
1262 
trySplit()1263         public EntrySpliterator<K,V> trySplit() {
1264             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1265             return (lo >= mid) ? null :
1266                 new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
1267                                        expectedModCount);
1268         }
1269 
1270 
forEachRemaining(Consumer<? super Map.Entry<K, V>> action)1271         public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
1272             int i, hi, mc;
1273             if (action == null)
1274                 throw new NullPointerException();
1275             WeakHashMap<K,V> m = map;
1276             WeakHashMap.Entry<K,V>[] tab = m.table;
1277             if ((hi = fence) < 0) {
1278                 mc = expectedModCount = m.modCount;
1279                 hi = fence = tab.length;
1280             }
1281             else
1282                 mc = expectedModCount;
1283             if (tab.length >= hi && (i = index) >= 0 &&
1284                 (i < (index = hi) || current != null)) {
1285                 WeakHashMap.Entry<K,V> p = current;
1286                 current = null; // exhaust
1287                 do {
1288                     if (p == null)
1289                         p = tab[i++];
1290                     else {
1291                         Object x = p.get();
1292                         V v = p.value;
1293                         p = p.next;
1294                         if (x != null) {
1295                             @SuppressWarnings("unchecked") K k =
1296                                 (K) WeakHashMap.unmaskNull(x);
1297                             action.accept
1298                                 (new AbstractMap.SimpleImmutableEntry<>(k, v));
1299                         }
1300                     }
1301                 } while (p != null || i < hi);
1302             }
1303             if (m.modCount != mc)
1304                 throw new ConcurrentModificationException();
1305         }
1306 
tryAdvance(Consumer<? super Map.Entry<K,V>> action)1307         public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
1308             int hi;
1309             if (action == null)
1310                 throw new NullPointerException();
1311             WeakHashMap.Entry<K,V>[] tab = map.table;
1312             if (tab.length >= (hi = getFence()) && index >= 0) {
1313                 while (current != null || index < hi) {
1314                     if (current == null)
1315                         current = tab[index++];
1316                     else {
1317                         Object x = current.get();
1318                         V v = current.value;
1319                         current = current.next;
1320                         if (x != null) {
1321                             @SuppressWarnings("unchecked") K k =
1322                                 (K) WeakHashMap.unmaskNull(x);
1323                             action.accept
1324                                 (new AbstractMap.SimpleImmutableEntry<>(k, v));
1325                             if (map.modCount != expectedModCount)
1326                                 throw new ConcurrentModificationException();
1327                             return true;
1328                         }
1329                     }
1330                 }
1331             }
1332             return false;
1333         }
1334 
characteristics()1335         public int characteristics() {
1336             return Spliterator.DISTINCT;
1337         }
1338     }
1339 
1340 }
1341