WeakHashMap.java revision 0976dc2e109a3ca2bd977d18eee74e4b7c9ada30
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
27package java.util;
28import java.lang.ref.WeakReference;
29import java.lang.ref.ReferenceQueue;
30import java.util.function.BiConsumer;
31import java.util.function.BiFunction;
32import 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}/../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 */
135public 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    /**
193     * The default threshold of map capacity above which alternative hashing is
194     * used for String keys. Alternative hashing reduces the incidence of
195     * collisions due to weak hash code calculation for String keys.
196     * <p/>
197     * This value may be overridden by defining the system property
198     * {@code jdk.map.althashing.threshold}. A property value of {@code 1}
199     * forces alternative hashing to be used at all times whereas
200     * {@code -1} value ensures that alternative hashing is never used.
201     */
202    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
203
204    /**
205     * holds values which can't be initialized until after VM is booted.
206     */
207    private static class Holder {
208
209        /**
210         * Table capacity above which to switch to use alternative hashing.
211         */
212        static final int ALTERNATIVE_HASHING_THRESHOLD;
213
214        static {
215            String altThreshold = java.security.AccessController.doPrivileged(
216                new sun.security.action.GetPropertyAction(
217                    "jdk.map.althashing.threshold"));
218
219            int threshold;
220            try {
221                threshold = (null != altThreshold)
222                        ? Integer.parseInt(altThreshold)
223                        : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
224
225                // disable alternative hashing if -1
226                if (threshold == -1) {
227                    threshold = Integer.MAX_VALUE;
228                }
229
230                if (threshold < 0) {
231                    throw new IllegalArgumentException("value must be positive integer.");
232                }
233            } catch(IllegalArgumentException failed) {
234                throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
235            }
236            ALTERNATIVE_HASHING_THRESHOLD = threshold;
237        }
238    }
239
240    /**
241     * If {@code true} then perform alternate hashing to reduce the incidence of
242     * collisions due to weak hash code calculation.
243     */
244    transient boolean useAltHashing;
245
246    /**
247     * A randomizing value associated with this instance that is applied to
248     * hash code of keys to make hash collisions harder to find.
249     *
250     * This hash seed is only used if {@code useAltHashing} is true.
251     */
252    transient int hashSeed;
253
254    @SuppressWarnings("unchecked")
255    private Entry<K,V>[] newTable(int n) {
256        return (Entry<K,V>[]) new Entry[n];
257    }
258
259    /**
260     * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial
261     * capacity and the given load factor.
262     *
263     * @param  initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
264     * @param  loadFactor      The load factor of the <tt>WeakHashMap</tt>
265     * @throws IllegalArgumentException if the initial capacity is negative,
266     *         or if the load factor is nonpositive.
267     */
268    public WeakHashMap(int initialCapacity, float loadFactor) {
269        if (initialCapacity < 0)
270            throw new IllegalArgumentException("Illegal Initial Capacity: "+
271                                               initialCapacity);
272        if (initialCapacity > MAXIMUM_CAPACITY)
273            initialCapacity = MAXIMUM_CAPACITY;
274
275        if (loadFactor <= 0 || Float.isNaN(loadFactor))
276            throw new IllegalArgumentException("Illegal Load factor: "+
277                                               loadFactor);
278        int capacity = 1;
279        while (capacity < initialCapacity)
280            capacity <<= 1;
281        table = newTable(capacity);
282        this.loadFactor = loadFactor;
283        threshold = (int)(capacity * loadFactor);
284        useAltHashing = sun.misc.VM.isBooted() &&
285                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
286        if (useAltHashing) {
287            hashSeed = sun.misc.Hashing.randomHashSeed(this);
288        } else {
289            hashSeed = 0;
290        }
291    }
292
293    /**
294     * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial
295     * capacity and the default load factor (0.75).
296     *
297     * @param  initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
298     * @throws IllegalArgumentException if the initial capacity is negative
299     */
300    public WeakHashMap(int initialCapacity) {
301        this(initialCapacity, DEFAULT_LOAD_FACTOR);
302    }
303
304    /**
305     * Constructs a new, empty <tt>WeakHashMap</tt> with the default initial
306     * capacity (16) and load factor (0.75).
307     */
308    public WeakHashMap() {
309        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
310    }
311
312    /**
313     * Constructs a new <tt>WeakHashMap</tt> with the same mappings as the
314     * specified map.  The <tt>WeakHashMap</tt> is created with the default
315     * load factor (0.75) and an initial capacity sufficient to hold the
316     * mappings in the specified map.
317     *
318     * @param   m the map whose mappings are to be placed in this map
319     * @throws  NullPointerException if the specified map is null
320     * @since   1.3
321     */
322    public WeakHashMap(Map<? extends K, ? extends V> m) {
323        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
324                DEFAULT_INITIAL_CAPACITY),
325             DEFAULT_LOAD_FACTOR);
326        putAll(m);
327    }
328
329    // internal utilities
330
331    /**
332     * Value representing null keys inside tables.
333     */
334    private static final Object NULL_KEY = new Object();
335
336    /**
337     * Use NULL_KEY for key if it is null.
338     */
339    private static Object maskNull(Object key) {
340        return (key == null) ? NULL_KEY : key;
341    }
342
343    /**
344     * Returns internal representation of null key back to caller as null.
345     */
346    static Object unmaskNull(Object key) {
347        return (key == NULL_KEY) ? null : key;
348    }
349
350    /**
351     * Checks for equality of non-null reference x and possibly-null y.  By
352     * default uses Object.equals.
353     */
354    private static boolean eq(Object x, Object y) {
355        return x == y || x.equals(y);
356    }
357
358    /**
359     * Retrieve object hash code and applies a supplemental hash function to the
360     * result hash, which defends against poor quality hash functions.  This is
361     * critical because HashMap uses power-of-two length hash tables, that
362     * otherwise encounter collisions for hashCodes that do not differ
363     * in lower bits.
364     */
365    int hash(Object k) {
366
367        int h;
368        if (useAltHashing) {
369            h = hashSeed;
370            if (k instanceof String) {
371                return sun.misc.Hashing.stringHash32((String) k);
372            } else {
373                h ^= k.hashCode();
374            }
375        } else  {
376            h = k.hashCode();
377        }
378
379        // This function ensures that hashCodes that differ only by
380        // constant multiples at each bit position have a bounded
381        // number of collisions (approximately 8 at default load factor).
382        h ^= (h >>> 20) ^ (h >>> 12);
383        return h ^ (h >>> 7) ^ (h >>> 4);
384    }
385
386    /**
387     * Returns index for hash code h.
388     */
389    private static int indexFor(int h, int length) {
390        return h & (length-1);
391    }
392
393    /**
394     * Expunges stale entries from the table.
395     */
396    private void expungeStaleEntries() {
397        for (Object x; (x = queue.poll()) != null; ) {
398            synchronized (queue) {
399                @SuppressWarnings("unchecked")
400                    Entry<K,V> e = (Entry<K,V>) x;
401                int i = indexFor(e.hash, table.length);
402
403                Entry<K,V> prev = table[i];
404                Entry<K,V> p = prev;
405                while (p != null) {
406                    Entry<K,V> next = p.next;
407                    if (p == e) {
408                        if (prev == e)
409                            table[i] = next;
410                        else
411                            prev.next = next;
412                        // Must not null out e.next;
413                        // stale entries may be in use by a HashIterator
414                        e.value = null; // Help GC
415                        size--;
416                        break;
417                    }
418                    prev = p;
419                    p = next;
420                }
421            }
422        }
423    }
424
425    /**
426     * Returns the table after first expunging stale entries.
427     */
428    private Entry<K,V>[] getTable() {
429        expungeStaleEntries();
430        return table;
431    }
432
433    /**
434     * Returns the number of key-value mappings in this map.
435     * This result is a snapshot, and may not reflect unprocessed
436     * entries that will be removed before next attempted access
437     * because they are no longer referenced.
438     */
439    public int size() {
440        if (size == 0)
441            return 0;
442        expungeStaleEntries();
443        return size;
444    }
445
446    /**
447     * Returns <tt>true</tt> if this map contains no key-value mappings.
448     * This result is a snapshot, and may not reflect unprocessed
449     * entries that will be removed before next attempted access
450     * because they are no longer referenced.
451     */
452    public boolean isEmpty() {
453        return size() == 0;
454    }
455
456    /**
457     * Returns the value to which the specified key is mapped,
458     * or {@code null} if this map contains no mapping for the key.
459     *
460     * <p>More formally, if this map contains a mapping from a key
461     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
462     * key.equals(k))}, then this method returns {@code v}; otherwise
463     * it returns {@code null}.  (There can be at most one such mapping.)
464     *
465     * <p>A return value of {@code null} does not <i>necessarily</i>
466     * indicate that the map contains no mapping for the key; it's also
467     * possible that the map explicitly maps the key to {@code null}.
468     * The {@link #containsKey containsKey} operation may be used to
469     * distinguish these two cases.
470     *
471     * @see #put(Object, Object)
472     */
473    public V get(Object key) {
474        Object k = maskNull(key);
475        int h = hash(k);
476        Entry<K,V>[] tab = getTable();
477        int index = indexFor(h, tab.length);
478        Entry<K,V> e = tab[index];
479        while (e != null) {
480            if (e.hash == h && eq(k, e.get()))
481                return e.value;
482            e = e.next;
483        }
484        return null;
485    }
486
487    /**
488     * Returns <tt>true</tt> if this map contains a mapping for the
489     * specified key.
490     *
491     * @param  key   The key whose presence in this map is to be tested
492     * @return <tt>true</tt> if there is a mapping for <tt>key</tt>;
493     *         <tt>false</tt> otherwise
494     */
495    public boolean containsKey(Object key) {
496        return getEntry(key) != null;
497    }
498
499    /**
500     * Returns the entry associated with the specified key in this map.
501     * Returns null if the map contains no mapping for this key.
502     */
503    Entry<K,V> getEntry(Object key) {
504        Object k = maskNull(key);
505        int h = hash(k);
506        Entry<K,V>[] tab = getTable();
507        int index = indexFor(h, tab.length);
508        Entry<K,V> e = tab[index];
509        while (e != null && !(e.hash == h && eq(k, e.get())))
510            e = e.next;
511        return e;
512    }
513
514    /**
515     * Associates the specified value with the specified key in this map.
516     * If the map previously contained a mapping for this key, the old
517     * value is replaced.
518     *
519     * @param key key with which the specified value is to be associated.
520     * @param value value to be associated with the specified key.
521     * @return the previous value associated with <tt>key</tt>, or
522     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
523     *         (A <tt>null</tt> return can also indicate that the map
524     *         previously associated <tt>null</tt> with <tt>key</tt>.)
525     */
526    public V put(K key, V value) {
527        Object k = maskNull(key);
528        int h = hash(k);
529        Entry<K,V>[] tab = getTable();
530        int i = indexFor(h, tab.length);
531
532        for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
533            if (h == e.hash && eq(k, e.get())) {
534                V oldValue = e.value;
535                if (value != oldValue)
536                    e.value = value;
537                return oldValue;
538            }
539        }
540
541        modCount++;
542        Entry<K,V> e = tab[i];
543        tab[i] = new Entry<>(k, value, queue, h, e);
544        if (++size >= threshold)
545            resize(tab.length * 2);
546        return null;
547    }
548
549    /**
550     * Rehashes the contents of this map into a new array with a
551     * larger capacity.  This method is called automatically when the
552     * number of keys in this map reaches its threshold.
553     *
554     * If current capacity is MAXIMUM_CAPACITY, this method does not
555     * resize the map, but sets threshold to Integer.MAX_VALUE.
556     * This has the effect of preventing future calls.
557     *
558     * @param newCapacity the new capacity, MUST be a power of two;
559     *        must be greater than current capacity unless current
560     *        capacity is MAXIMUM_CAPACITY (in which case value
561     *        is irrelevant).
562     */
563    void resize(int newCapacity) {
564        Entry<K,V>[] oldTable = getTable();
565        int oldCapacity = oldTable.length;
566        if (oldCapacity == MAXIMUM_CAPACITY) {
567            threshold = Integer.MAX_VALUE;
568            return;
569        }
570
571        Entry<K,V>[] newTable = newTable(newCapacity);
572        boolean oldAltHashing = useAltHashing;
573        useAltHashing |= sun.misc.VM.isBooted() &&
574                (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
575        boolean rehash = oldAltHashing ^ useAltHashing;
576        if (rehash) {
577            hashSeed = sun.misc.Hashing.randomHashSeed(this);
578        }
579        transfer(oldTable, newTable, rehash);
580        table = newTable;
581
582        /*
583         * If ignoring null elements and processing ref queue caused massive
584         * shrinkage, then restore old table.  This should be rare, but avoids
585         * unbounded expansion of garbage-filled tables.
586         */
587        if (size >= threshold / 2) {
588            threshold = (int)(newCapacity * loadFactor);
589        } else {
590            expungeStaleEntries();
591            transfer(newTable, oldTable, false);
592            table = oldTable;
593        }
594    }
595
596    /** Transfers all entries from src to dest tables */
597    private void transfer(Entry<K,V>[] src, Entry<K,V>[] dest, boolean rehash) {
598        for (int j = 0; j < src.length; ++j) {
599            Entry<K,V> e = src[j];
600            src[j] = null;
601            while (e != null) {
602                Entry<K,V> next = e.next;
603                Object key = e.get();
604                if (key == null) {
605                    e.next = null;  // Help GC
606                    e.value = null; //  "   "
607                    size--;
608                } else {
609                    if (rehash) {
610                        e.hash = hash(key);
611                    }
612                    int i = indexFor(e.hash, dest.length);
613                    e.next = dest[i];
614                    dest[i] = e;
615                }
616                e = next;
617            }
618        }
619    }
620
621    /**
622     * Copies all of the mappings from the specified map to this map.
623     * These mappings will replace any mappings that this map had for any
624     * of the keys currently in the specified map.
625     *
626     * @param m mappings to be stored in this map.
627     * @throws  NullPointerException if the specified map is null.
628     */
629    public void putAll(Map<? extends K, ? extends V> m) {
630        int numKeysToBeAdded = m.size();
631        if (numKeysToBeAdded == 0)
632            return;
633
634        /*
635         * Expand the map if the map if the number of mappings to be added
636         * is greater than or equal to threshold.  This is conservative; the
637         * obvious condition is (m.size() + size) >= threshold, but this
638         * condition could result in a map with twice the appropriate capacity,
639         * if the keys to be added overlap with the keys already in this map.
640         * By using the conservative calculation, we subject ourself
641         * to at most one extra resize.
642         */
643        if (numKeysToBeAdded > threshold) {
644            int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
645            if (targetCapacity > MAXIMUM_CAPACITY)
646                targetCapacity = MAXIMUM_CAPACITY;
647            int newCapacity = table.length;
648            while (newCapacity < targetCapacity)
649                newCapacity <<= 1;
650            if (newCapacity > table.length)
651                resize(newCapacity);
652        }
653
654        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
655            put(e.getKey(), e.getValue());
656    }
657
658    /**
659     * Removes the mapping for a key from this weak hash map if it is present.
660     * More formally, if this map contains a mapping from key <tt>k</tt> to
661     * value <tt>v</tt> such that <code>(key==null ?  k==null :
662     * key.equals(k))</code>, that mapping is removed.  (The map can contain
663     * at most one such mapping.)
664     *
665     * <p>Returns the value to which this map previously associated the key,
666     * or <tt>null</tt> if the map contained no mapping for the key.  A
667     * return value of <tt>null</tt> does not <i>necessarily</i> indicate
668     * that the map contained no mapping for the key; it's also possible
669     * that the map explicitly mapped the key to <tt>null</tt>.
670     *
671     * <p>The map will not contain a mapping for the specified key once the
672     * call returns.
673     *
674     * @param key key whose mapping is to be removed from the map
675     * @return the previous value associated with <tt>key</tt>, or
676     *         <tt>null</tt> if there was no mapping for <tt>key</tt>
677     */
678    public V remove(Object key) {
679        Object k = maskNull(key);
680        int h = hash(k);
681        Entry<K,V>[] tab = getTable();
682        int i = indexFor(h, tab.length);
683        Entry<K,V> prev = tab[i];
684        Entry<K,V> e = prev;
685
686        while (e != null) {
687            Entry<K,V> next = e.next;
688            if (h == e.hash && eq(k, e.get())) {
689                modCount++;
690                size--;
691                if (prev == e)
692                    tab[i] = next;
693                else
694                    prev.next = next;
695                return e.value;
696            }
697            prev = e;
698            e = next;
699        }
700
701        return null;
702    }
703
704    /** Special version of remove needed by Entry set */
705    boolean removeMapping(Object o) {
706        if (!(o instanceof Map.Entry))
707            return false;
708        Entry<K,V>[] tab = getTable();
709        Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
710        Object k = maskNull(entry.getKey());
711        int h = hash(k);
712        int i = indexFor(h, tab.length);
713        Entry<K,V> prev = tab[i];
714        Entry<K,V> e = prev;
715
716        while (e != null) {
717            Entry<K,V> next = e.next;
718            if (h == e.hash && e.equals(entry)) {
719                modCount++;
720                size--;
721                if (prev == e)
722                    tab[i] = next;
723                else
724                    prev.next = next;
725                return true;
726            }
727            prev = e;
728            e = next;
729        }
730
731        return false;
732    }
733
734    /**
735     * Removes all of the mappings from this map.
736     * The map will be empty after this call returns.
737     */
738    public void clear() {
739        // clear out ref queue. We don't need to expunge entries
740        // since table is getting cleared.
741        while (queue.poll() != null)
742            ;
743
744        modCount++;
745        Arrays.fill(table, null);
746        size = 0;
747
748        // Allocation of array may have caused GC, which may have caused
749        // additional entries to go stale.  Removing these entries from the
750        // reference queue will make them eligible for reclamation.
751        while (queue.poll() != null)
752            ;
753    }
754
755    /**
756     * Returns <tt>true</tt> if this map maps one or more keys to the
757     * specified value.
758     *
759     * @param value value whose presence in this map is to be tested
760     * @return <tt>true</tt> if this map maps one or more keys to the
761     *         specified value
762     */
763    public boolean containsValue(Object value) {
764        if (value==null)
765            return containsNullValue();
766
767        Entry<K,V>[] tab = getTable();
768        for (int i = tab.length; i-- > 0;)
769            for (Entry<K,V> e = tab[i]; e != null; e = e.next)
770                if (value.equals(e.value))
771                    return true;
772        return false;
773    }
774
775    /**
776     * Special-case code for containsValue with null argument
777     */
778    private boolean containsNullValue() {
779        Entry<K,V>[] tab = getTable();
780        for (int i = tab.length; i-- > 0;)
781            for (Entry<K,V> e = tab[i]; e != null; e = e.next)
782                if (e.value==null)
783                    return true;
784        return false;
785    }
786
787    /**
788     * The entries in this hash table extend WeakReference, using its main ref
789     * field as the key.
790     */
791    private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
792        V value;
793        int hash;
794        Entry<K,V> next;
795
796        /**
797         * Creates new entry.
798         */
799        Entry(Object key, V value,
800              ReferenceQueue<Object> queue,
801              int hash, Entry<K,V> next) {
802            super(key, queue);
803            this.value = value;
804            this.hash  = hash;
805            this.next  = next;
806        }
807
808        @SuppressWarnings("unchecked")
809        public K getKey() {
810            return (K) WeakHashMap.unmaskNull(get());
811        }
812
813        public V getValue() {
814            return value;
815        }
816
817        public V setValue(V newValue) {
818            V oldValue = value;
819            value = newValue;
820            return oldValue;
821        }
822
823        public boolean equals(Object o) {
824            if (!(o instanceof Map.Entry))
825                return false;
826            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
827            K k1 = getKey();
828            Object k2 = e.getKey();
829            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
830                V v1 = getValue();
831                Object v2 = e.getValue();
832                if (v1 == v2 || (v1 != null && v1.equals(v2)))
833                    return true;
834            }
835            return false;
836        }
837
838        public int hashCode() {
839            K k = getKey();
840            V v = getValue();
841            return ((k==null ? 0 : k.hashCode()) ^
842                    (v==null ? 0 : v.hashCode()));
843        }
844
845        public String toString() {
846            return getKey() + "=" + getValue();
847        }
848    }
849
850    private abstract class HashIterator<T> implements Iterator<T> {
851        private int index;
852        private Entry<K,V> entry = null;
853        private Entry<K,V> lastReturned = null;
854        private int expectedModCount = modCount;
855
856        /**
857         * Strong reference needed to avoid disappearance of key
858         * between hasNext and next
859         */
860        private Object nextKey = null;
861
862        /**
863         * Strong reference needed to avoid disappearance of key
864         * between nextEntry() and any use of the entry
865         */
866        private Object currentKey = null;
867
868        HashIterator() {
869            index = isEmpty() ? 0 : table.length;
870        }
871
872        public boolean hasNext() {
873            Entry<K,V>[] t = table;
874
875            while (nextKey == null) {
876                Entry<K,V> e = entry;
877                int i = index;
878                while (e == null && i > 0)
879                    e = t[--i];
880                entry = e;
881                index = i;
882                if (e == null) {
883                    currentKey = null;
884                    return false;
885                }
886                nextKey = e.get(); // hold on to key in strong ref
887                if (nextKey == null)
888                    entry = entry.next;
889            }
890            return true;
891        }
892
893        /** The common parts of next() across different types of iterators */
894        protected Entry<K,V> nextEntry() {
895            if (modCount != expectedModCount)
896                throw new ConcurrentModificationException();
897            if (nextKey == null && !hasNext())
898                throw new NoSuchElementException();
899
900            lastReturned = entry;
901            entry = entry.next;
902            currentKey = nextKey;
903            nextKey = null;
904            return lastReturned;
905        }
906
907        public void remove() {
908            if (lastReturned == null)
909                throw new IllegalStateException();
910            if (modCount != expectedModCount)
911                throw new ConcurrentModificationException();
912
913            WeakHashMap.this.remove(currentKey);
914            expectedModCount = modCount;
915            lastReturned = null;
916            currentKey = null;
917        }
918
919    }
920
921    private class ValueIterator extends HashIterator<V> {
922        public V next() {
923            return nextEntry().value;
924        }
925    }
926
927    private class KeyIterator extends HashIterator<K> {
928        public K next() {
929            return nextEntry().getKey();
930        }
931    }
932
933    private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
934        public Map.Entry<K,V> next() {
935            return nextEntry();
936        }
937    }
938
939    // Views
940
941    private transient Set<Map.Entry<K,V>> entrySet = null;
942
943    /**
944     * Returns a {@link Set} view of the keys contained in this map.
945     * The set is backed by the map, so changes to the map are
946     * reflected in the set, and vice-versa.  If the map is modified
947     * while an iteration over the set is in progress (except through
948     * the iterator's own <tt>remove</tt> operation), the results of
949     * the iteration are undefined.  The set supports element removal,
950     * which removes the corresponding mapping from the map, via the
951     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
952     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
953     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
954     * operations.
955     */
956    public Set<K> keySet() {
957        Set<K> ks = keySet;
958        return (ks != null ? ks : (keySet = new KeySet()));
959    }
960
961    private class KeySet extends AbstractSet<K> {
962        public Iterator<K> iterator() {
963            return new KeyIterator();
964        }
965
966        public int size() {
967            return WeakHashMap.this.size();
968        }
969
970        public boolean contains(Object o) {
971            return containsKey(o);
972        }
973
974        public boolean remove(Object o) {
975            if (containsKey(o)) {
976                WeakHashMap.this.remove(o);
977                return true;
978            }
979            else
980                return false;
981        }
982
983        public void clear() {
984            WeakHashMap.this.clear();
985        }
986
987        public Spliterator<K> spliterator() {
988            return new KeySpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
989        }
990    }
991
992    /**
993     * Returns a {@link Collection} view of the values contained in this map.
994     * The collection is backed by the map, so changes to the map are
995     * reflected in the collection, and vice-versa.  If the map is
996     * modified while an iteration over the collection is in progress
997     * (except through the iterator's own <tt>remove</tt> operation),
998     * the results of the iteration are undefined.  The collection
999     * supports element removal, which removes the corresponding
1000     * mapping from the map, via the <tt>Iterator.remove</tt>,
1001     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1002     * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
1003     * support the <tt>add</tt> or <tt>addAll</tt> operations.
1004     */
1005    public Collection<V> values() {
1006        Collection<V> vs = values;
1007        return (vs != null) ? vs : (values = new Values());
1008    }
1009
1010    private class Values extends AbstractCollection<V> {
1011        public Iterator<V> iterator() {
1012            return new ValueIterator();
1013        }
1014
1015        public int size() {
1016            return WeakHashMap.this.size();
1017        }
1018
1019        public boolean contains(Object o) {
1020            return containsValue(o);
1021        }
1022
1023        public void clear() {
1024            WeakHashMap.this.clear();
1025        }
1026
1027        public Spliterator<V> spliterator() {
1028            return new ValueSpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
1029        }
1030    }
1031
1032    /**
1033     * Returns a {@link Set} view of the mappings contained in this map.
1034     * The set is backed by the map, so changes to the map are
1035     * reflected in the set, and vice-versa.  If the map is modified
1036     * while an iteration over the set is in progress (except through
1037     * the iterator's own <tt>remove</tt> operation, or through the
1038     * <tt>setValue</tt> operation on a map entry returned by the
1039     * iterator) the results of the iteration are undefined.  The set
1040     * supports element removal, which removes the corresponding
1041     * mapping from the map, via the <tt>Iterator.remove</tt>,
1042     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
1043     * <tt>clear</tt> operations.  It does not support the
1044     * <tt>add</tt> or <tt>addAll</tt> operations.
1045     */
1046    public Set<Map.Entry<K,V>> entrySet() {
1047        Set<Map.Entry<K,V>> es = entrySet;
1048        return es != null ? es : (entrySet = new EntrySet());
1049    }
1050
1051    private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1052        public Iterator<Map.Entry<K,V>> iterator() {
1053            return new EntryIterator();
1054        }
1055
1056        public boolean contains(Object o) {
1057            if (!(o instanceof Map.Entry))
1058                return false;
1059            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1060            Entry<K,V> candidate = getEntry(e.getKey());
1061            return candidate != null && candidate.equals(e);
1062        }
1063
1064        public boolean remove(Object o) {
1065            return removeMapping(o);
1066        }
1067
1068        public int size() {
1069            return WeakHashMap.this.size();
1070        }
1071
1072        public void clear() {
1073            WeakHashMap.this.clear();
1074        }
1075
1076        private List<Map.Entry<K,V>> deepCopy() {
1077            List<Map.Entry<K,V>> list = new ArrayList<>(size());
1078            for (Map.Entry<K,V> e : this)
1079                list.add(new AbstractMap.SimpleEntry<>(e));
1080            return list;
1081        }
1082
1083        public Object[] toArray() {
1084            return deepCopy().toArray();
1085        }
1086
1087        public <T> T[] toArray(T[] a) {
1088            return deepCopy().toArray(a);
1089        }
1090
1091        public Spliterator<Map.Entry<K,V>> spliterator() {
1092            return new EntrySpliterator<>(WeakHashMap.this, 0, -1, 0, 0);
1093        }
1094    }
1095
1096    @SuppressWarnings("unchecked")
1097    @Override
1098    public void forEach(BiConsumer<? super K, ? super V> action) {
1099        Objects.requireNonNull(action);
1100        int expectedModCount = modCount;
1101
1102        Entry<K, V>[] tab = getTable();
1103        for (Entry<K, V> entry : tab) {
1104            while (entry != null) {
1105                Object key = entry.get();
1106                if (key != null) {
1107                    action.accept((K)WeakHashMap.unmaskNull(key), entry.value);
1108                }
1109                entry = entry.next;
1110
1111                if (expectedModCount != modCount) {
1112                    throw new ConcurrentModificationException();
1113                }
1114            }
1115        }
1116    }
1117
1118    @SuppressWarnings("unchecked")
1119    @Override
1120    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1121        Objects.requireNonNull(function);
1122        int expectedModCount = modCount;
1123
1124        Entry<K, V>[] tab = getTable();
1125        for (Entry<K, V> entry : tab) {
1126            while (entry != null) {
1127                Object key = entry.get();
1128                if (key != null) {
1129                    entry.value = function.apply((K)WeakHashMap.unmaskNull(key), entry.value);
1130                }
1131                entry = entry.next;
1132
1133                if (expectedModCount != modCount) {
1134                    throw new ConcurrentModificationException();
1135                }
1136            }
1137        }
1138    }
1139
1140
1141    /**
1142     * Similar form as other hash Spliterators, but skips dead
1143     * elements.
1144     */
1145    static class WeakHashMapSpliterator<K,V> {
1146        final WeakHashMap<K,V> map;
1147        WeakHashMap.Entry<K,V> current; // current node
1148        int index;             // current index, modified on advance/split
1149        int fence;             // -1 until first use; then one past last index
1150        int est;               // size estimate
1151        int expectedModCount;  // for comodification checks
1152
1153        WeakHashMapSpliterator(WeakHashMap<K,V> m, int origin,
1154                               int fence, int est,
1155                               int expectedModCount) {
1156            this.map = m;
1157            this.index = origin;
1158            this.fence = fence;
1159            this.est = est;
1160            this.expectedModCount = expectedModCount;
1161        }
1162
1163        final int getFence() { // initialize fence and size on first use
1164            int hi;
1165            if ((hi = fence) < 0) {
1166                WeakHashMap<K,V> m = map;
1167                est = m.size();
1168                expectedModCount = m.modCount;
1169                hi = fence = m.table.length;
1170            }
1171            return hi;
1172        }
1173
1174        public final long estimateSize() {
1175            getFence(); // force init
1176            return (long) est;
1177        }
1178    }
1179
1180    static final class KeySpliterator<K,V>
1181        extends WeakHashMapSpliterator<K,V>
1182        implements Spliterator<K> {
1183        KeySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1184                       int expectedModCount) {
1185            super(m, origin, fence, est, expectedModCount);
1186        }
1187
1188        public KeySpliterator<K,V> trySplit() {
1189            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1190            return (lo >= mid) ? null :
1191                new KeySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
1192                                        expectedModCount);
1193        }
1194
1195        public void forEachRemaining(Consumer<? super K> action) {
1196            int i, hi, mc;
1197            if (action == null)
1198                throw new NullPointerException();
1199            WeakHashMap<K,V> m = map;
1200            WeakHashMap.Entry<K,V>[] tab = m.table;
1201            if ((hi = fence) < 0) {
1202                mc = expectedModCount = m.modCount;
1203                hi = fence = tab.length;
1204            }
1205            else
1206                mc = expectedModCount;
1207            if (tab.length >= hi && (i = index) >= 0 &&
1208                (i < (index = hi) || current != null)) {
1209                WeakHashMap.Entry<K,V> p = current;
1210                current = null; // exhaust
1211                do {
1212                    if (p == null)
1213                        p = tab[i++];
1214                    else {
1215                        Object x = p.get();
1216                        p = p.next;
1217                        if (x != null) {
1218                            @SuppressWarnings("unchecked") K k =
1219                                (K) WeakHashMap.unmaskNull(x);
1220                            action.accept(k);
1221                        }
1222                    }
1223                } while (p != null || i < hi);
1224            }
1225            if (m.modCount != mc)
1226                throw new ConcurrentModificationException();
1227        }
1228
1229        public boolean tryAdvance(Consumer<? super K> action) {
1230            int hi;
1231            if (action == null)
1232                throw new NullPointerException();
1233            WeakHashMap.Entry<K,V>[] tab = map.table;
1234            if (tab.length >= (hi = getFence()) && index >= 0) {
1235                while (current != null || index < hi) {
1236                    if (current == null)
1237                        current = tab[index++];
1238                    else {
1239                        Object x = current.get();
1240                        current = current.next;
1241                        if (x != null) {
1242                            @SuppressWarnings("unchecked") K k =
1243                                (K) WeakHashMap.unmaskNull(x);
1244                            action.accept(k);
1245                            if (map.modCount != expectedModCount)
1246                                throw new ConcurrentModificationException();
1247                            return true;
1248                        }
1249                    }
1250                }
1251            }
1252            return false;
1253        }
1254
1255        public int characteristics() {
1256            return Spliterator.DISTINCT;
1257        }
1258    }
1259
1260    static final class ValueSpliterator<K,V>
1261        extends WeakHashMapSpliterator<K,V>
1262        implements Spliterator<V> {
1263        ValueSpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1264                         int expectedModCount) {
1265            super(m, origin, fence, est, expectedModCount);
1266        }
1267
1268        public ValueSpliterator<K,V> trySplit() {
1269            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1270            return (lo >= mid) ? null :
1271                new ValueSpliterator<K,V>(map, lo, index = mid, est >>>= 1,
1272                                          expectedModCount);
1273        }
1274
1275        public void forEachRemaining(Consumer<? super V> action) {
1276            int i, hi, mc;
1277            if (action == null)
1278                throw new NullPointerException();
1279            WeakHashMap<K,V> m = map;
1280            WeakHashMap.Entry<K,V>[] tab = m.table;
1281            if ((hi = fence) < 0) {
1282                mc = expectedModCount = m.modCount;
1283                hi = fence = tab.length;
1284            }
1285            else
1286                mc = expectedModCount;
1287            if (tab.length >= hi && (i = index) >= 0 &&
1288                (i < (index = hi) || current != null)) {
1289                WeakHashMap.Entry<K,V> p = current;
1290                current = null; // exhaust
1291                do {
1292                    if (p == null)
1293                        p = tab[i++];
1294                    else {
1295                        Object x = p.get();
1296                        V v = p.value;
1297                        p = p.next;
1298                        if (x != null)
1299                            action.accept(v);
1300                    }
1301                } while (p != null || i < hi);
1302            }
1303            if (m.modCount != mc)
1304                throw new ConcurrentModificationException();
1305        }
1306
1307        public boolean tryAdvance(Consumer<? super 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                            action.accept(v);
1322                            if (map.modCount != expectedModCount)
1323                                throw new ConcurrentModificationException();
1324                            return true;
1325                        }
1326                    }
1327                }
1328            }
1329            return false;
1330        }
1331
1332        public int characteristics() {
1333            return 0;
1334        }
1335    }
1336
1337    static final class EntrySpliterator<K,V>
1338        extends WeakHashMapSpliterator<K,V>
1339        implements Spliterator<Map.Entry<K,V>> {
1340        EntrySpliterator(WeakHashMap<K,V> m, int origin, int fence, int est,
1341                       int expectedModCount) {
1342            super(m, origin, fence, est, expectedModCount);
1343        }
1344
1345        public EntrySpliterator<K,V> trySplit() {
1346            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1347            return (lo >= mid) ? null :
1348                new EntrySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
1349                                          expectedModCount);
1350        }
1351
1352
1353        public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
1354            int i, hi, mc;
1355            if (action == null)
1356                throw new NullPointerException();
1357            WeakHashMap<K,V> m = map;
1358            WeakHashMap.Entry<K,V>[] tab = m.table;
1359            if ((hi = fence) < 0) {
1360                mc = expectedModCount = m.modCount;
1361                hi = fence = tab.length;
1362            }
1363            else
1364                mc = expectedModCount;
1365            if (tab.length >= hi && (i = index) >= 0 &&
1366                (i < (index = hi) || current != null)) {
1367                WeakHashMap.Entry<K,V> p = current;
1368                current = null; // exhaust
1369                do {
1370                    if (p == null)
1371                        p = tab[i++];
1372                    else {
1373                        Object x = p.get();
1374                        V v = p.value;
1375                        p = p.next;
1376                        if (x != null) {
1377                            @SuppressWarnings("unchecked") K k =
1378                                (K) WeakHashMap.unmaskNull(x);
1379                            action.accept
1380                                (new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
1381                        }
1382                    }
1383                } while (p != null || i < hi);
1384            }
1385            if (m.modCount != mc)
1386                throw new ConcurrentModificationException();
1387        }
1388
1389        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
1390            int hi;
1391            if (action == null)
1392                throw new NullPointerException();
1393            WeakHashMap.Entry<K,V>[] tab = map.table;
1394            if (tab.length >= (hi = getFence()) && index >= 0) {
1395                while (current != null || index < hi) {
1396                    if (current == null)
1397                        current = tab[index++];
1398                    else {
1399                        Object x = current.get();
1400                        V v = current.value;
1401                        current = current.next;
1402                        if (x != null) {
1403                            @SuppressWarnings("unchecked") K k =
1404                                (K) WeakHashMap.unmaskNull(x);
1405                            action.accept
1406                                (new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
1407                            if (map.modCount != expectedModCount)
1408                                throw new ConcurrentModificationException();
1409                            return true;
1410                        }
1411                    }
1412                }
1413            }
1414            return false;
1415        }
1416
1417        public int characteristics() {
1418            return Spliterator.DISTINCT;
1419        }
1420    }
1421
1422}
1423