• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.util;
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 <tt>Map</tt> interface, with
37  * <em>weak keys</em>.
38  * An entry in a <tt>WeakHashMap</tt> 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 <tt>Map</tt>
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 <tt>HashMap</tt>
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 <tt>WeakHashMap</tt> 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  * <tt>equals</tt> methods test for object identity using the
58  * <tt>==</tt> 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  * <tt>WeakHashMap</tt> 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 <tt>equals</tt> methods are not based upon object identity, such
63  * as <tt>String</tt> instances.  With such recreatable key objects,
64  * however, the automatic removal of <tt>WeakHashMap</tt> entries whose
65  * keys have been discarded may prove to be confusing.
66  *
67  * <p> The behavior of the <tt>WeakHashMap</tt> class depends in part upon
68  * the actions of the garbage collector, so several familiar (though not
69  * required) <tt>Map</tt> invariants do not hold for this class.  Because
70  * the garbage collector may discard keys at any time, a
71  * <tt>WeakHashMap</tt> may behave as though an unknown thread is silently
72  * removing entries.  In particular, even if you synchronize on a
73  * <tt>WeakHashMap</tt> instance and invoke none of its mutator methods, it
74  * is possible for the <tt>size</tt> method to return smaller values over
75  * time, for the <tt>isEmpty</tt> method to return <tt>false</tt> and
76  * then <tt>true</tt>, for the <tt>containsKey</tt> method to return
77  * <tt>true</tt> and later <tt>false</tt> for a given key, for the
78  * <tt>get</tt> method to return a value for a given key but later return
79  * <tt>null</tt>, for the <tt>put</tt> method to return
80  * <tt>null</tt> and the <tt>remove</tt> method to return
81  * <tt>false</tt> 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 <tt>WeakHashMap</tt> 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  * <tt>WeakHashMap</tt> 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 <tt>WeakHashMap</tt> 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  * <tt>WeakReferences</tt> before
101  * inserting, as in: <tt>m.put(key, new WeakReference(value))</tt>,
102  * and then unwrapping upon each <tt>get</tt>.
103  *
104  * <p>The iterators returned by the <tt>iterator</tt> 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  * <tt>remove</tt> 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 <tt>ConcurrentModificationException</tt> 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}openjdk-redirect.html?v=8&path=/technotes/guides/collections/index.html">
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 <tt>WeakHashMap</tt> with the given initial
199      * capacity and the given load factor.
200      *
201      * @param  initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
202      * @param  loadFactor      The load factor of the <tt>WeakHashMap</tt>
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 <tt>WeakHashMap</tt> with the given initial
226      * capacity and the default load factor (0.75).
227      *
228      * @param  initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
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 <tt>WeakHashMap</tt> 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 <tt>WeakHashMap</tt> with the same mappings as the
245      * specified map.  The <tt>WeakHashMap</tt> 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) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
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      */
eq(Object x, Object y)285     private static boolean eq(Object x, Object y) {
286         return x == y || x.equals(y);
287     }
288 
289     /**
290      * Returns index for hash code h.
291      */
indexFor(int h, int length)292     private static int indexFor(int h, int length) {
293         return h & (length-1);
294     }
295 
296     /**
297      * Expunges stale entries from the table.
298      */
expungeStaleEntries()299     private void expungeStaleEntries() {
300         for (Object x; (x = queue.poll()) != null; ) {
301             synchronized (queue) {
302                 @SuppressWarnings("unchecked")
303                     Entry<K,V> e = (Entry<K,V>) x;
304                 int i = indexFor(e.hash, table.length);
305 
306                 Entry<K,V> prev = table[i];
307                 Entry<K,V> p = prev;
308                 while (p != null) {
309                     Entry<K,V> next = p.next;
310                     if (p == e) {
311                         if (prev == e)
312                             table[i] = next;
313                         else
314                             prev.next = next;
315                         // Must not null out e.next;
316                         // stale entries may be in use by a HashIterator
317                         e.value = null; // Help GC
318                         size--;
319                         break;
320                     }
321                     prev = p;
322                     p = next;
323                 }
324             }
325         }
326     }
327 
328     /**
329      * Returns the table after first expunging stale entries.
330      */
getTable()331     private Entry<K,V>[] getTable() {
332         expungeStaleEntries();
333         return table;
334     }
335 
336     /**
337      * Returns the number of key-value mappings in this map.
338      * This result is a snapshot, and may not reflect unprocessed
339      * entries that will be removed before next attempted access
340      * because they are no longer referenced.
341      */
size()342     public int size() {
343         if (size == 0)
344             return 0;
345         expungeStaleEntries();
346         return size;
347     }
348 
349     /**
350      * Returns <tt>true</tt> if this map contains no key-value mappings.
351      * This result is a snapshot, and may not reflect unprocessed
352      * entries that will be removed before next attempted access
353      * because they are no longer referenced.
354      */
isEmpty()355     public boolean isEmpty() {
356         return size() == 0;
357     }
358 
359     /**
360      * Returns the value to which the specified key is mapped,
361      * or {@code null} if this map contains no mapping for the key.
362      *
363      * <p>More formally, if this map contains a mapping from a key
364      * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
365      * key.equals(k))}, then this method returns {@code v}; otherwise
366      * it returns {@code null}.  (There can be at most one such mapping.)
367      *
368      * <p>A return value of {@code null} does not <i>necessarily</i>
369      * indicate that the map contains no mapping for the key; it's also
370      * possible that the map explicitly maps the key to {@code null}.
371      * The {@link #containsKey containsKey} operation may be used to
372      * distinguish these two cases.
373      *
374      * @see #put(Object, Object)
375      */
get(Object key)376     public V get(Object key) {
377         Object k = maskNull(key);
378         int h = sun.misc.Hashing.singleWordWangJenkinsHash(k);
379         Entry<K,V>[] tab = getTable();
380         int index = indexFor(h, tab.length);
381         Entry<K,V> e = tab[index];
382         while (e != null) {
383             if (e.hash == h && eq(k, e.get()))
384                 return e.value;
385             e = e.next;
386         }
387         return null;
388     }
389 
390     /**
391      * Returns <tt>true</tt> if this map contains a mapping for the
392      * specified key.
393      *
394      * @param  key   The key whose presence in this map is to be tested
395      * @return <tt>true</tt> if there is a mapping for <tt>key</tt>;
396      *         <tt>false</tt> otherwise
397      */
containsKey(Object key)398     public boolean containsKey(Object key) {
399         return getEntry(key) != null;
400     }
401 
402     /**
403      * Returns the entry associated with the specified key in this map.
404      * Returns null if the map contains no mapping for this key.
405      */
getEntry(Object key)406     Entry<K,V> getEntry(Object key) {
407         Object k = maskNull(key);
408         int h = sun.misc.Hashing.singleWordWangJenkinsHash(k);
409         Entry<K,V>[] tab = getTable();
410         int index = indexFor(h, tab.length);
411         Entry<K,V> e = tab[index];
412         while (e != null && !(e.hash == h && eq(k, e.get())))
413             e = e.next;
414         return e;
415     }
416 
417     /**
418      * Associates the specified value with the specified key in this map.
419      * If the map previously contained a mapping for this key, the old
420      * value is replaced.
421      *
422      * @param key key with which the specified value is to be associated.
423      * @param value value to be associated with the specified key.
424      * @return the previous value associated with <tt>key</tt>, or
425      *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
426      *         (A <tt>null</tt> return can also indicate that the map
427      *         previously associated <tt>null</tt> with <tt>key</tt>.)
428      */
put(K key, V value)429     public V put(K key, V value) {
430         Object k = maskNull(key);
431         int h = sun.misc.Hashing.singleWordWangJenkinsHash(k);
432         Entry<K,V>[] tab = getTable();
433         int i = indexFor(h, tab.length);
434 
435         for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
436             if (h == e.hash && eq(k, e.get())) {
437                 V oldValue = e.value;
438                 if (value != oldValue)
439                     e.value = value;
440                 return oldValue;
441             }
442         }
443 
444         modCount++;
445         Entry<K,V> e = tab[i];
446         tab[i] = new Entry<>(k, value, queue, h, e);
447         if (++size >= threshold)
448             resize(tab.length * 2);
449         return null;
450     }
451 
452     /**
453      * Rehashes the contents of this map into a new array with a
454      * larger capacity.  This method is called automatically when the
455      * number of keys in this map reaches its threshold.
456      *
457      * If current capacity is MAXIMUM_CAPACITY, this method does not
458      * resize the map, but sets threshold to Integer.MAX_VALUE.
459      * This has the effect of preventing future calls.
460      *
461      * @param newCapacity the new capacity, MUST be a power of two;
462      *        must be greater than current capacity unless current
463      *        capacity is MAXIMUM_CAPACITY (in which case value
464      *        is irrelevant).
465      */
resize(int newCapacity)466     void resize(int newCapacity) {
467         Entry<K,V>[] oldTable = getTable();
468         int oldCapacity = oldTable.length;
469         if (oldCapacity == MAXIMUM_CAPACITY) {
470             threshold = Integer.MAX_VALUE;
471             return;
472         }
473 
474         Entry<K,V>[] newTable = newTable(newCapacity);
475         transfer(oldTable, newTable);
476         table = newTable;
477 
478         /*
479          * If ignoring null elements and processing ref queue caused massive
480          * shrinkage, then restore old table.  This should be rare, but avoids
481          * unbounded expansion of garbage-filled tables.
482          */
483         if (size >= threshold / 2) {
484             threshold = (int)(newCapacity * loadFactor);
485         } else {
486             expungeStaleEntries();
487             transfer(newTable, oldTable);
488             table = oldTable;
489         }
490     }
491 
492     /** Transfers all entries from src to dest tables */
transfer(Entry<K,V>[] src, Entry<K,V>[] dest)493     private void transfer(Entry<K,V>[] src, Entry<K,V>[] dest) {
494         for (int j = 0; j < src.length; ++j) {
495             Entry<K,V> e = src[j];
496             src[j] = null;
497             while (e != null) {
498                 Entry<K,V> next = e.next;
499                 Object key = e.get();
500                 if (key == null) {
501                     e.next = null;  // Help GC
502                     e.value = null; //  "   "
503                     size--;
504                 } else {
505                     int i = indexFor(e.hash, dest.length);
506                     e.next = dest[i];
507                     dest[i] = e;
508                 }
509                 e = next;
510             }
511         }
512     }
513 
514     /**
515      * Copies all of the mappings from the specified map to this map.
516      * These mappings will replace any mappings that this map had for any
517      * of the keys currently in the specified map.
518      *
519      * @param m mappings to be stored in this map.
520      * @throws  NullPointerException if the specified map is null.
521      */
putAll(Map<? extends K, ? extends V> m)522     public void putAll(Map<? extends K, ? extends V> m) {
523         int numKeysToBeAdded = m.size();
524         if (numKeysToBeAdded == 0)
525             return;
526 
527         /*
528          * Expand the map if the map if the number of mappings to be added
529          * is greater than or equal to threshold.  This is conservative; the
530          * obvious condition is (m.size() + size) >= threshold, but this
531          * condition could result in a map with twice the appropriate capacity,
532          * if the keys to be added overlap with the keys already in this map.
533          * By using the conservative calculation, we subject ourself
534          * to at most one extra resize.
535          */
536         if (numKeysToBeAdded > threshold) {
537             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
538             if (targetCapacity > MAXIMUM_CAPACITY)
539                 targetCapacity = MAXIMUM_CAPACITY;
540             int newCapacity = table.length;
541             while (newCapacity < targetCapacity)
542                 newCapacity <<= 1;
543             if (newCapacity > table.length)
544                 resize(newCapacity);
545         }
546 
547         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
548             put(e.getKey(), e.getValue());
549     }
550 
551     /**
552      * Removes the mapping for a key from this weak hash map if it is present.
553      * More formally, if this map contains a mapping from key <tt>k</tt> to
554      * value <tt>v</tt> such that <code>(key==null ?  k==null :
555      * key.equals(k))</code>, that mapping is removed.  (The map can contain
556      * at most one such mapping.)
557      *
558      * <p>Returns the value to which this map previously associated the key,
559      * or <tt>null</tt> if the map contained no mapping for the key.  A
560      * return value of <tt>null</tt> does not <i>necessarily</i> indicate
561      * that the map contained no mapping for the key; it's also possible
562      * that the map explicitly mapped the key to <tt>null</tt>.
563      *
564      * <p>The map will not contain a mapping for the specified key once the
565      * call returns.
566      *
567      * @param key key whose mapping is to be removed from the map
568      * @return the previous value associated with <tt>key</tt>, or
569      *         <tt>null</tt> if there was no mapping for <tt>key</tt>
570      */
remove(Object key)571     public V remove(Object key) {
572         Object k = maskNull(key);
573         int h = sun.misc.Hashing.singleWordWangJenkinsHash(k);
574         Entry<K,V>[] tab = getTable();
575         int i = indexFor(h, tab.length);
576         Entry<K,V> prev = tab[i];
577         Entry<K,V> e = prev;
578 
579         while (e != null) {
580             Entry<K,V> next = e.next;
581             if (h == e.hash && eq(k, e.get())) {
582                 modCount++;
583                 size--;
584                 if (prev == e)
585                     tab[i] = next;
586                 else
587                     prev.next = next;
588                 return e.value;
589             }
590             prev = e;
591             e = next;
592         }
593 
594         return null;
595     }
596 
597     /** Special version of remove needed by Entry set */
removeMapping(Object o)598     boolean removeMapping(Object o) {
599         if (!(o instanceof Map.Entry))
600             return false;
601         Entry<K,V>[] tab = getTable();
602         Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
603         Object k = maskNull(entry.getKey());
604         int h = sun.misc.Hashing.singleWordWangJenkinsHash(k);
605         int i = indexFor(h, tab.length);
606         Entry<K,V> prev = tab[i];
607         Entry<K,V> e = prev;
608 
609         while (e != null) {
610             Entry<K,V> next = e.next;
611             if (h == e.hash && e.equals(entry)) {
612                 modCount++;
613                 size--;
614                 if (prev == e)
615                     tab[i] = next;
616                 else
617                     prev.next = next;
618                 return true;
619             }
620             prev = e;
621             e = next;
622         }
623 
624         return false;
625     }
626 
627     /**
628      * Removes all of the mappings from this map.
629      * The map will be empty after this call returns.
630      */
clear()631     public void clear() {
632         // clear out ref queue. We don't need to expunge entries
633         // since table is getting cleared.
634         while (queue.poll() != null)
635             ;
636 
637         modCount++;
638         Arrays.fill(table, null);
639         size = 0;
640 
641         // Allocation of array may have caused GC, which may have caused
642         // additional entries to go stale.  Removing these entries from the
643         // reference queue will make them eligible for reclamation.
644         while (queue.poll() != null)
645             ;
646     }
647 
648     /**
649      * Returns <tt>true</tt> if this map maps one or more keys to the
650      * specified value.
651      *
652      * @param value value whose presence in this map is to be tested
653      * @return <tt>true</tt> if this map maps one or more keys to the
654      *         specified value
655      */
containsValue(Object value)656     public boolean containsValue(Object value) {
657         if (value==null)
658             return containsNullValue();
659 
660         Entry<K,V>[] tab = getTable();
661         for (int i = tab.length; i-- > 0;)
662             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
663                 if (value.equals(e.value))
664                     return true;
665         return false;
666     }
667 
668     /**
669      * Special-case code for containsValue with null argument
670      */
containsNullValue()671     private boolean containsNullValue() {
672         Entry<K,V>[] tab = getTable();
673         for (int i = tab.length; i-- > 0;)
674             for (Entry<K,V> e = tab[i]; e != null; e = e.next)
675                 if (e.value==null)
676                     return true;
677         return false;
678     }
679 
680     /**
681      * The entries in this hash table extend WeakReference, using its main ref
682      * field as the key.
683      */
684     private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
685         V value;
686         int hash;
687         Entry<K,V> next;
688 
689         /**
690          * Creates new entry.
691          */
Entry(Object key, V value, ReferenceQueue<Object> queue, int hash, Entry<K,V> next)692         Entry(Object key, V value,
693               ReferenceQueue<Object> queue,
694               int hash, Entry<K,V> next) {
695             super(key, queue);
696             this.value = value;
697             this.hash  = hash;
698             this.next  = next;
699         }
700 
701         @SuppressWarnings("unchecked")
getKey()702         public K getKey() {
703             return (K) WeakHashMap.unmaskNull(get());
704         }
705 
getValue()706         public V getValue() {
707             return value;
708         }
709 
setValue(V newValue)710         public V setValue(V newValue) {
711             V oldValue = value;
712             value = newValue;
713             return oldValue;
714         }
715 
equals(Object o)716         public boolean equals(Object o) {
717             if (!(o instanceof Map.Entry))
718                 return false;
719             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
720             K k1 = getKey();
721             Object k2 = e.getKey();
722             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
723                 V v1 = getValue();
724                 Object v2 = e.getValue();
725                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
726                     return true;
727             }
728             return false;
729         }
730 
hashCode()731         public int hashCode() {
732             K k = getKey();
733             V v = getValue();
734             return ((k==null ? 0 : k.hashCode()) ^
735                     (v==null ? 0 : v.hashCode()));
736         }
737 
toString()738         public String toString() {
739             return getKey() + "=" + getValue();
740         }
741     }
742 
743     private abstract class HashIterator<T> implements Iterator<T> {
744         private int index;
745         private Entry<K,V> entry = null;
746         private Entry<K,V> lastReturned = null;
747         private int expectedModCount = modCount;
748 
749         /**
750          * Strong reference needed to avoid disappearance of key
751          * between hasNext and next
752          */
753         private Object nextKey = null;
754 
755         /**
756          * Strong reference needed to avoid disappearance of key
757          * between nextEntry() and any use of the entry
758          */
759         private Object currentKey = null;
760 
HashIterator()761         HashIterator() {
762             index = isEmpty() ? 0 : table.length;
763         }
764 
hasNext()765         public boolean hasNext() {
766             Entry<K,V>[] t = table;
767 
768             while (nextKey == null) {
769                 Entry<K,V> e = entry;
770                 int i = index;
771                 while (e == null && i > 0)
772                     e = t[--i];
773                 entry = e;
774                 index = i;
775                 if (e == null) {
776                     currentKey = null;
777                     return false;
778                 }
779                 nextKey = e.get(); // hold on to key in strong ref
780                 if (nextKey == null)
781                     entry = entry.next;
782             }
783             return true;
784         }
785 
786         /** The common parts of next() across different types of iterators */
nextEntry()787         protected Entry<K,V> nextEntry() {
788             if (modCount != expectedModCount)
789                 throw new ConcurrentModificationException();
790             if (nextKey == null && !hasNext())
791                 throw new NoSuchElementException();
792 
793             lastReturned = entry;
794             entry = entry.next;
795             currentKey = nextKey;
796             nextKey = null;
797             return lastReturned;
798         }
799 
remove()800         public void remove() {
801             if (lastReturned == null)
802                 throw new IllegalStateException();
803             if (modCount != expectedModCount)
804                 throw new ConcurrentModificationException();
805 
806             WeakHashMap.this.remove(currentKey);
807             expectedModCount = modCount;
808             lastReturned = null;
809             currentKey = null;
810         }
811 
812     }
813 
814     private class ValueIterator extends HashIterator<V> {
next()815         public V next() {
816             return nextEntry().value;
817         }
818     }
819 
820     private class KeyIterator extends HashIterator<K> {
next()821         public K next() {
822             return nextEntry().getKey();
823         }
824     }
825 
826     private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
next()827         public Map.Entry<K,V> next() {
828             return nextEntry();
829         }
830     }
831 
832     // Views
833 
834     private transient Set<Map.Entry<K,V>> entrySet = null;
835 
836     /**
837      * Returns a {@link Set} view of the keys contained in this map.
838      * The set is backed by the map, so changes to the map are
839      * reflected in the set, and vice-versa.  If the map is modified
840      * while an iteration over the set is in progress (except through
841      * the iterator's own <tt>remove</tt> operation), the results of
842      * the iteration are undefined.  The set supports element removal,
843      * which removes the corresponding mapping from the map, via the
844      * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
845      * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
846      * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
847      * operations.
848      */
keySet()849     public Set<K> keySet() {
850         Set<K> ks = keySet;
851         return (ks != null ? ks : (keySet = new KeySet()));
852     }
853 
854     private class KeySet extends AbstractSet<K> {
iterator()855         public Iterator<K> iterator() {
856             return new KeyIterator();
857         }
858 
size()859         public int size() {
860             return WeakHashMap.this.size();
861         }
862 
contains(Object o)863         public boolean contains(Object o) {
864             return containsKey(o);
865         }
866 
remove(Object o)867         public boolean remove(Object o) {
868             if (containsKey(o)) {
869                 WeakHashMap.this.remove(o);
870                 return true;
871             }
872             else
873                 return false;
874         }
875 
clear()876         public void clear() {
877             WeakHashMap.this.clear();
878         }
879 
spliterator()880         public Spliterator<K> spliterator() {
881             return new KeySpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
882         }
883     }
884 
885     /**
886      * Returns a {@link Collection} view of the values contained in this map.
887      * The collection is backed by the map, so changes to the map are
888      * reflected in the collection, and vice-versa.  If the map is
889      * modified while an iteration over the collection is in progress
890      * (except through the iterator's own <tt>remove</tt> operation),
891      * the results of the iteration are undefined.  The collection
892      * supports element removal, which removes the corresponding
893      * mapping from the map, via the <tt>Iterator.remove</tt>,
894      * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
895      * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
896      * support the <tt>add</tt> or <tt>addAll</tt> operations.
897      */
values()898     public Collection<V> values() {
899         Collection<V> vs = values;
900         return (vs != null) ? vs : (values = new Values());
901     }
902 
903     private class Values extends AbstractCollection<V> {
iterator()904         public Iterator<V> iterator() {
905             return new ValueIterator();
906         }
907 
size()908         public int size() {
909             return WeakHashMap.this.size();
910         }
911 
contains(Object o)912         public boolean contains(Object o) {
913             return containsValue(o);
914         }
915 
clear()916         public void clear() {
917             WeakHashMap.this.clear();
918         }
919 
spliterator()920         public Spliterator<V> spliterator() {
921             return new ValueSpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
922         }
923     }
924 
925     /**
926      * Returns a {@link Set} view of the mappings contained in this map.
927      * The set is backed by the map, so changes to the map are
928      * reflected in the set, and vice-versa.  If the map is modified
929      * while an iteration over the set is in progress (except through
930      * the iterator's own <tt>remove</tt> operation, or through the
931      * <tt>setValue</tt> operation on a map entry returned by the
932      * iterator) the results of the iteration are undefined.  The set
933      * supports element removal, which removes the corresponding
934      * mapping from the map, via the <tt>Iterator.remove</tt>,
935      * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
936      * <tt>clear</tt> operations.  It does not support the
937      * <tt>add</tt> or <tt>addAll</tt> operations.
938      */
entrySet()939     public Set<Map.Entry<K,V>> entrySet() {
940         Set<Map.Entry<K,V>> es = entrySet;
941         return es != null ? es : (entrySet = new EntrySet());
942     }
943 
944     private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
iterator()945         public Iterator<Map.Entry<K,V>> iterator() {
946             return new EntryIterator();
947         }
948 
contains(Object o)949         public boolean contains(Object o) {
950             if (!(o instanceof Map.Entry))
951                 return false;
952             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
953             Entry<K,V> candidate = getEntry(e.getKey());
954             return candidate != null && candidate.equals(e);
955         }
956 
remove(Object o)957         public boolean remove(Object o) {
958             return removeMapping(o);
959         }
960 
size()961         public int size() {
962             return WeakHashMap.this.size();
963         }
964 
clear()965         public void clear() {
966             WeakHashMap.this.clear();
967         }
968 
deepCopy()969         private List<Map.Entry<K,V>> deepCopy() {
970             List<Map.Entry<K,V>> list = new ArrayList<>(size());
971             for (Map.Entry<K,V> e : this)
972                 list.add(new AbstractMap.SimpleEntry<>(e));
973             return list;
974         }
975 
toArray()976         public Object[] toArray() {
977             return deepCopy().toArray();
978         }
979 
toArray(T[] a)980         public <T> T[] toArray(T[] a) {
981             return deepCopy().toArray(a);
982         }
983 
spliterator()984         public Spliterator<Map.Entry<K,V>> spliterator() {
985             return new EntrySpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
986         }
987     }
988 
989     @SuppressWarnings("unchecked")
990     @Override
forEach(BiConsumer<? super K, ? super V> action)991     public void forEach(BiConsumer<? super K, ? super V> action) {
992         Objects.requireNonNull(action);
993         int expectedModCount = modCount;
994 
995         Entry<K, V>[] tab = getTable();
996         for (Entry<K, V> entry : tab) {
997             while (entry != null) {
998                 Object key = entry.get();
999                 if (key != null) {
1000                     action.accept((K)WeakHashMap.unmaskNull(key), entry.value);
1001                 }
1002                 entry = entry.next;
1003 
1004                 if (expectedModCount != modCount) {
1005                     throw new ConcurrentModificationException();
1006                 }
1007             }
1008         }
1009     }
1010 
1011     @SuppressWarnings("unchecked")
1012     @Override
replaceAll(BiFunction<? super K, ? super V, ? extends V> function)1013     public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1014         Objects.requireNonNull(function);
1015         int expectedModCount = modCount;
1016 
1017         Entry<K, V>[] tab = getTable();
1018         for (Entry<K, V> entry : tab) {
1019             while (entry != null) {
1020                 Object key = entry.get();
1021                 if (key != null) {
1022                     entry.value = function.apply((K)WeakHashMap.unmaskNull(key), entry.value);
1023                 }
1024                 entry = entry.next;
1025 
1026                 if (expectedModCount != modCount) {
1027                     throw new ConcurrentModificationException();
1028                 }
1029             }
1030         }
1031     }
1032 
1033 
1034     /**
1035      * Similar form as other hash Spliterators, but skips dead
1036      * elements.
1037      */
1038     static class WeakHashMapSpliterator<K,V> {
1039         final WeakHashMap<K,V> map;
1040         WeakHashMap.Entry<K,V> current; // current node
1041         int index;             // current index, modified on advance/split
1042         int fence;             // -1 until first use; then one past last index
1043         int est;               // size estimate
1044         int expectedModCount;  // for comodification checks
1045 
WeakHashMapSpliterator(WeakHashMap<K,V> m, int origin, int fence, int est, int expectedModCount)1046         WeakHashMapSpliterator(WeakHashMap<K,V> m, int origin,
1047                                int fence, int est,
1048                                int expectedModCount) {
1049             this.map = m;
1050             this.index = origin;
1051             this.fence = fence;
1052             this.est = est;
1053             this.expectedModCount = expectedModCount;
1054         }
1055 
getFence()1056         final int getFence() { // initialize fence and size on first use
1057             int hi;
1058             if ((hi = fence) < 0) {
1059                 WeakHashMap<K,V> m = map;
1060                 est = m.size();
1061                 expectedModCount = m.modCount;
1062                 hi = fence = m.table.length;
1063             }
1064             return hi;
1065         }
1066 
estimateSize()1067         public final long estimateSize() {
1068             getFence(); // force init
1069             return (long) est;
1070         }
1071     }
1072 
1073     static final class KeySpliterator<K,V>
1074         extends WeakHashMapSpliterator<K,V>
1075         implements Spliterator<K> {
KeySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est, int expectedModCount)1076         KeySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1077                        int expectedModCount) {
1078             super(m, origin, fence, est, expectedModCount);
1079         }
1080 
trySplit()1081         public KeySpliterator<K,V> trySplit() {
1082             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1083             return (lo >= mid) ? null :
1084                 new KeySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
1085                                         expectedModCount);
1086         }
1087 
forEachRemaining(Consumer<? super K> action)1088         public void forEachRemaining(Consumer<? super K> action) {
1089             int i, hi, mc;
1090             if (action == null)
1091                 throw new NullPointerException();
1092             WeakHashMap<K,V> m = map;
1093             WeakHashMap.Entry<K,V>[] tab = m.table;
1094             if ((hi = fence) < 0) {
1095                 mc = expectedModCount = m.modCount;
1096                 hi = fence = tab.length;
1097             }
1098             else
1099                 mc = expectedModCount;
1100             if (tab.length >= hi && (i = index) >= 0 &&
1101                 (i < (index = hi) || current != null)) {
1102                 WeakHashMap.Entry<K,V> p = current;
1103                 current = null; // exhaust
1104                 do {
1105                     if (p == null)
1106                         p = tab[i++];
1107                     else {
1108                         Object x = p.get();
1109                         p = p.next;
1110                         if (x != null) {
1111                             @SuppressWarnings("unchecked") K k =
1112                                 (K) WeakHashMap.unmaskNull(x);
1113                             action.accept(k);
1114                         }
1115                     }
1116                 } while (p != null || i < hi);
1117             }
1118             if (m.modCount != mc)
1119                 throw new ConcurrentModificationException();
1120         }
1121 
tryAdvance(Consumer<? super K> action)1122         public boolean tryAdvance(Consumer<? super K> action) {
1123             int hi;
1124             if (action == null)
1125                 throw new NullPointerException();
1126             WeakHashMap.Entry<K,V>[] tab = map.table;
1127             if (tab.length >= (hi = getFence()) && index >= 0) {
1128                 while (current != null || index < hi) {
1129                     if (current == null)
1130                         current = tab[index++];
1131                     else {
1132                         Object x = current.get();
1133                         current = current.next;
1134                         if (x != null) {
1135                             @SuppressWarnings("unchecked") K k =
1136                                 (K) WeakHashMap.unmaskNull(x);
1137                             action.accept(k);
1138                             if (map.modCount != expectedModCount)
1139                                 throw new ConcurrentModificationException();
1140                             return true;
1141                         }
1142                     }
1143                 }
1144             }
1145             return false;
1146         }
1147 
characteristics()1148         public int characteristics() {
1149             return Spliterator.DISTINCT;
1150         }
1151     }
1152 
1153     static final class ValueSpliterator<K,V>
1154         extends WeakHashMapSpliterator<K,V>
1155         implements Spliterator<V> {
ValueSpliterator(WeakHashMap<K,V> m, int origin, int fence, int est, int expectedModCount)1156         ValueSpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1157                          int expectedModCount) {
1158             super(m, origin, fence, est, expectedModCount);
1159         }
1160 
trySplit()1161         public ValueSpliterator<K,V> trySplit() {
1162             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1163             return (lo >= mid) ? null :
1164                 new ValueSpliterator<K,V>(map, lo, index = mid, est >>>= 1,
1165                                           expectedModCount);
1166         }
1167 
forEachRemaining(Consumer<? super V> action)1168         public void forEachRemaining(Consumer<? super V> action) {
1169             int i, hi, mc;
1170             if (action == null)
1171                 throw new NullPointerException();
1172             WeakHashMap<K,V> m = map;
1173             WeakHashMap.Entry<K,V>[] tab = m.table;
1174             if ((hi = fence) < 0) {
1175                 mc = expectedModCount = m.modCount;
1176                 hi = fence = tab.length;
1177             }
1178             else
1179                 mc = expectedModCount;
1180             if (tab.length >= hi && (i = index) >= 0 &&
1181                 (i < (index = hi) || current != null)) {
1182                 WeakHashMap.Entry<K,V> p = current;
1183                 current = null; // exhaust
1184                 do {
1185                     if (p == null)
1186                         p = tab[i++];
1187                     else {
1188                         Object x = p.get();
1189                         V v = p.value;
1190                         p = p.next;
1191                         if (x != null)
1192                             action.accept(v);
1193                     }
1194                 } while (p != null || i < hi);
1195             }
1196             if (m.modCount != mc)
1197                 throw new ConcurrentModificationException();
1198         }
1199 
tryAdvance(Consumer<? super V> action)1200         public boolean tryAdvance(Consumer<? super V> action) {
1201             int hi;
1202             if (action == null)
1203                 throw new NullPointerException();
1204             WeakHashMap.Entry<K,V>[] tab = map.table;
1205             if (tab.length >= (hi = getFence()) && index >= 0) {
1206                 while (current != null || index < hi) {
1207                     if (current == null)
1208                         current = tab[index++];
1209                     else {
1210                         Object x = current.get();
1211                         V v = current.value;
1212                         current = current.next;
1213                         if (x != null) {
1214                             action.accept(v);
1215                             if (map.modCount != expectedModCount)
1216                                 throw new ConcurrentModificationException();
1217                             return true;
1218                         }
1219                     }
1220                 }
1221             }
1222             return false;
1223         }
1224 
characteristics()1225         public int characteristics() {
1226             return 0;
1227         }
1228     }
1229 
1230     static final class EntrySpliterator<K,V>
1231         extends WeakHashMapSpliterator<K,V>
1232         implements Spliterator<Map.Entry<K,V>> {
EntrySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est, int expectedModCount)1233         EntrySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1234                        int expectedModCount) {
1235             super(m, origin, fence, est, expectedModCount);
1236         }
1237 
trySplit()1238         public EntrySpliterator<K,V> trySplit() {
1239             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1240             return (lo >= mid) ? null :
1241                 new EntrySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
1242                                           expectedModCount);
1243         }
1244 
1245 
forEachRemaining(Consumer<? super Map.Entry<K, V>> action)1246         public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
1247             int i, hi, mc;
1248             if (action == null)
1249                 throw new NullPointerException();
1250             WeakHashMap<K,V> m = map;
1251             WeakHashMap.Entry<K,V>[] tab = m.table;
1252             if ((hi = fence) < 0) {
1253                 mc = expectedModCount = m.modCount;
1254                 hi = fence = tab.length;
1255             }
1256             else
1257                 mc = expectedModCount;
1258             if (tab.length >= hi && (i = index) >= 0 &&
1259                 (i < (index = hi) || current != null)) {
1260                 WeakHashMap.Entry<K,V> p = current;
1261                 current = null; // exhaust
1262                 do {
1263                     if (p == null)
1264                         p = tab[i++];
1265                     else {
1266                         Object x = p.get();
1267                         V v = p.value;
1268                         p = p.next;
1269                         if (x != null) {
1270                             @SuppressWarnings("unchecked") K k =
1271                                 (K) WeakHashMap.unmaskNull(x);
1272                             action.accept
1273                                 (new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
1274                         }
1275                     }
1276                 } while (p != null || i < hi);
1277             }
1278             if (m.modCount != mc)
1279                 throw new ConcurrentModificationException();
1280         }
1281 
tryAdvance(Consumer<? super Map.Entry<K,V>> action)1282         public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
1283             int hi;
1284             if (action == null)
1285                 throw new NullPointerException();
1286             WeakHashMap.Entry<K,V>[] tab = map.table;
1287             if (tab.length >= (hi = getFence()) && index >= 0) {
1288                 while (current != null || index < hi) {
1289                     if (current == null)
1290                         current = tab[index++];
1291                     else {
1292                         Object x = current.get();
1293                         V v = current.value;
1294                         current = current.next;
1295                         if (x != null) {
1296                             @SuppressWarnings("unchecked") K k =
1297                                 (K) WeakHashMap.unmaskNull(x);
1298                             action.accept
1299                                 (new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
1300                             if (map.modCount != expectedModCount)
1301                                 throw new ConcurrentModificationException();
1302                             return true;
1303                         }
1304                     }
1305                 }
1306             }
1307             return false;
1308         }
1309 
characteristics()1310         public int characteristics() {
1311             return Spliterator.DISTINCT;
1312         }
1313     }
1314 
1315 }
1316