ConcurrentReferenceHashMap.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. /*
  18.  * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
  19.  */

  20. package org.apache.commons.collections4.map;

  21. /*
  22.  * Written by Doug Lea with assistance from members of JCP JSR-166
  23.  * Expert Group and released to the public domain, as explained at
  24.  * http://creativecommons.org/licenses/publicdomain
  25.  */

  26. import java.lang.ref.Reference;
  27. import java.lang.ref.ReferenceQueue;
  28. import java.lang.ref.SoftReference;
  29. import java.lang.ref.WeakReference;
  30. import java.util.AbstractCollection;
  31. import java.util.AbstractMap;
  32. import java.util.AbstractSet;
  33. import java.util.Arrays;
  34. import java.util.Collection;
  35. import java.util.ConcurrentModificationException;
  36. import java.util.EnumSet;
  37. import java.util.Enumeration;
  38. import java.util.HashMap;
  39. import java.util.Hashtable;
  40. import java.util.IdentityHashMap;
  41. import java.util.Iterator;
  42. import java.util.Map;
  43. import java.util.NoSuchElementException;
  44. import java.util.Objects;
  45. import java.util.Set;
  46. import java.util.concurrent.ConcurrentMap;
  47. import java.util.concurrent.locks.ReentrantLock;
  48. import java.util.function.BiFunction;
  49. import java.util.function.Function;
  50. import java.util.function.Supplier;

  51. /**
  52.  * An advanced hash map supporting configurable garbage collection semantics of keys and values, optional referential-equality, full concurrency of retrievals,
  53.  * and adjustable expected concurrency for updates.
  54.  * <p>
  55.  * This map is designed around specific advanced use-cases. If there is any doubt whether this map is for you, you most likely should be using
  56.  * {@link java.util.concurrent.ConcurrentHashMap} instead.
  57.  * </p>
  58.  * <p>
  59.  * This map supports strong, weak, and soft keys and values. By default, keys are weak, and values are strong. Such a configuration offers similar behavior to
  60.  * {@link java.util.WeakHashMap}, entries of this map are periodically removed once their corresponding keys are no longer referenced outside of this map. In
  61.  * other words, this map will not prevent a key from being discarded by the garbage collector. Once a key has been discarded by the collector, the corresponding
  62.  * entry is no longer visible to this map; however, the entry may occupy space until a future map operation decides to reclaim it. For this reason, summary
  63.  * functions such as {@code size} and {@code isEmpty} might return a value greater than the observed number of entries. In order to support a high level of
  64.  * concurrency, stale entries are only reclaimed during blocking (usually mutating) operations.
  65.  * </p>
  66.  * <p>
  67.  * Enabling soft keys allows entries in this map to remain until their space is absolutely needed by the garbage collector. This is unlike weak keys which can
  68.  * be reclaimed as soon as they are no longer referenced by a normal strong reference. The primary use case for soft keys is a cache, which ideally occupies
  69.  * memory that is not in use for as long as possible.
  70.  * </p>
  71.  * <p>
  72.  * By default, values are held using a normal strong reference. This provides the commonly desired guarantee that a value will always have at least the same
  73.  * life-span as its key. For this reason, care should be taken to ensure that a value never refers, either directly or indirectly, to its key, thereby
  74.  * preventing reclamation. If this is unavoidable, then it is recommended to use the same reference type in use for the key. However, it should be noted that
  75.  * non-strong values may disappear before their corresponding key.
  76.  * </p>
  77.  * <p>
  78.  * While this map does allow the use of both strong keys and values, it is recommended you use {@link java.util.concurrent.ConcurrentHashMap} for such a
  79.  * configuration, since it is optimized for that case.
  80.  * </p>
  81.  * <p>
  82.  * Just like {@link java.util.concurrent.ConcurrentHashMap}, this class obeys the same functional specification as {@link Hashtable}, and includes versions of
  83.  * methods corresponding to each method of {@code Hashtable}. However, even though all operations are thread-safe, retrieval operations do <em>not</em> entail
  84.  * locking, and there is <em>not</em> any support for locking the entire map in a way that prevents all access. This class is fully interoperable with
  85.  * {@code Hashtable} in programs that rely on its thread safety but not on its synchronization details.
  86.  * </p>
  87.  * <p>
  88.  * Retrieval operations (including {@code get}) generally do not block, so they may overlap with update operations (including {@code put} and {@code remove}).
  89.  * Retrievals reflect the results of the most recently <em>completed</em> update operations holding upon their onset. For aggregate operations such as
  90.  * {@code putAll} and {@code clear}, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators and Enumerations return
  91.  * elements reflecting the state of the hash map at some point at or since the creation of the iterator/enumeration. They do <em>not</em> throw
  92.  * {@link ConcurrentModificationException}. However, iterators are designed to be used by only one thread at a time.
  93.  * </p>
  94.  * <p>
  95.  * The allowed concurrency among update operations is guided by the optional {@code concurrencyLevel} constructor argument (default
  96.  * {@value #DEFAULT_CONCURRENCY_LEVEL}), which is used as a hint for internal sizing. The map is internally partitioned to try to permit the indicated number of
  97.  * concurrent updates without contention. Because placement in hash tables is essentially random, the actual concurrency will vary. Ideally, you should choose a
  98.  * value to accommodate as many threads as will ever concurrently modify the map. Using a significantly higher value than you need can waste space and time, and
  99.  * a significantly lower value can lead to thread contention. But overestimates and underestimates within an order of magnitude do not usually have much
  100.  * noticeable impact. A value of one is appropriate when it is known that only one thread will modify and all others will only read. Also, resizing this or any
  101.  * other kind of hash map is a relatively slow operation, so, when possible, it is a good idea that you provide estimates of expected map sizes in constructors.
  102.  * </p>
  103.  * <p>
  104.  * This class and its views and iterators implement all of the <em>optional</em> methods of the {@link Map} and {@link Iterator} interfaces.
  105.  * </p>
  106.  * <p>
  107.  * Like {@link Hashtable} but unlike {@link HashMap}, this class does <em>not</em> allow {@code null} to be used as a key or value.
  108.  * </p>
  109.  * <p>
  110.  * Provenance: Copied and edited from Apache Groovy git master at commit 77dc80a7512ceb2168b1bc866c3d0c69b002fe11; via Doug Lea, Jason T. Greene, with
  111.  * assistance from members of JCP JSR-166, and Hazelcast.
  112.  * </p>
  113.  *
  114.  * @param <K> the type of keys maintained by this map.
  115.  * @param <V> the type of mapped values.
  116.  */
  117. public class ConcurrentReferenceHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> {

  118.     /**
  119.      * Builds new ConcurrentReferenceHashMap instances.
  120.      * <p>
  121.      * By default, keys are weak, and values are strong.
  122.      * </p>
  123.      * <p>
  124.      * The default values are:
  125.      * </p>
  126.      * <ul>
  127.      * <li>concurrency level: {@value #DEFAULT_CONCURRENCY_LEVEL}</li>
  128.      * <li>initial capacity: {@value #DEFAULT_INITIAL_CAPACITY}</li>
  129.      * <li>key reference type: {@link ReferenceType#WEAK}</li>
  130.      * <li>load factor: {@value #DEFAULT_LOAD_FACTOR}</li>
  131.      * <li>options: {@code null}</li>
  132.      * <li>source map: {@code null}</li>
  133.      * <li>value reference type: {@link ReferenceType#STRONG}</li>
  134.      * </ul>
  135.      *
  136.      * @param <K> the type of keys.
  137.      * @param <V> the type of values.
  138.      */
  139.     public static class Builder<K, V> implements Supplier<ConcurrentReferenceHashMap<K, V>> {

  140.         private static final Map<?, ?> DEFAULT_SOURCE_MAP = null;

  141.         private int initialCapacity = DEFAULT_INITIAL_CAPACITY;
  142.         private float loadFactor = DEFAULT_LOAD_FACTOR;
  143.         private int concurrencyLevel = DEFAULT_CONCURRENCY_LEVEL;
  144.         private ReferenceType keyReferenceType = DEFAULT_KEY_TYPE;
  145.         private ReferenceType valueReferenceType = DEFAULT_VALUE_TYPE;
  146.         private EnumSet<Option> options = DEFAULT_OPTIONS;
  147.         @SuppressWarnings("unchecked")
  148.         private Map<? extends K, ? extends V> sourceMap = (Map<? extends K, ? extends V>) DEFAULT_SOURCE_MAP;

  149.         /**
  150.          * Constructs a new instances of {@link ConcurrentReferenceHashMap}.
  151.          */
  152.         public Builder() {
  153.             // empty
  154.         }

  155.         /**
  156.          * Builds a new {@link ConcurrentReferenceHashMap}.
  157.          * <p>
  158.          * By default, keys are weak, and values are strong.
  159.          * </p>
  160.          * <p>
  161.          * The default values are:
  162.          * </p>
  163.          * <ul>
  164.          * <li>concurrency level: {@value #DEFAULT_CONCURRENCY_LEVEL}</li>
  165.          * <li>initial capacity: {@value #DEFAULT_INITIAL_CAPACITY}</li>
  166.          * <li>key reference type: {@link ReferenceType#WEAK}</li>
  167.          * <li>load factor: {@value #DEFAULT_LOAD_FACTOR}</li>
  168.          * <li>options: {@code null}</li>
  169.          * <li>source map: {@code null}</li>
  170.          * <li>value reference type: {@link ReferenceType#STRONG}</li>
  171.          * </ul>
  172.          */
  173.         @Override
  174.         public ConcurrentReferenceHashMap<K, V> get() {
  175.             final ConcurrentReferenceHashMap<K, V> map = new ConcurrentReferenceHashMap<>(initialCapacity, loadFactor, concurrencyLevel, keyReferenceType,
  176.                     valueReferenceType, options);
  177.             if (sourceMap != null) {
  178.                 map.putAll(sourceMap);
  179.             }
  180.             return map;
  181.         }

  182.         /**
  183.          * Sets the estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this many threads.
  184.          *
  185.          * @param concurrencyLevel estimated number of concurrently updating threads
  186.          * @return this instance.
  187.          */
  188.         public Builder<K, V> setConcurrencyLevel(final int concurrencyLevel) {
  189.             this.concurrencyLevel = concurrencyLevel;
  190.             return this;
  191.         }

  192.         /**
  193.          * Sets the initial capacity. The implementation performs internal sizing to accommodate this many elements.
  194.          *
  195.          * @param initialCapacity the initial capacity.
  196.          * @return this instance.
  197.          */
  198.         public Builder<K, V> setInitialCapacity(final int initialCapacity) {
  199.             this.initialCapacity = initialCapacity;
  200.             return this;
  201.         }

  202.         /**
  203.          * Sets the reference type to use for keys.
  204.          *
  205.          * @param keyReferenceType the reference type to use for keys.
  206.          * @return this instance.
  207.          */
  208.         public Builder<K, V> setKeyReferenceType(final ReferenceType keyReferenceType) {
  209.             this.keyReferenceType = keyReferenceType;
  210.             return this;
  211.         }

  212.         /**
  213.          * Sets the load factor factor, used to control resizing. Resizing may be performed when the average number of elements per bin exceeds this threshold.
  214.          *
  215.          * @param loadFactor the load factor factor, used to control resizing
  216.          * @return this instance.
  217.          */
  218.         public Builder<K, V> setLoadFactor(final float loadFactor) {
  219.             this.loadFactor = loadFactor;
  220.             return this;
  221.         }

  222.         /**
  223.          * Sets the behavioral options.
  224.          *
  225.          * @param options the behavioral options.
  226.          * @return this instance.
  227.          */
  228.         public Builder<K, V> setOptions(final EnumSet<Option> options) {
  229.             this.options = options;
  230.             return this;
  231.         }

  232.         /**
  233.          * Sets the values to load into a new map.
  234.          *
  235.          * @param sourceMap the values to load into a new map.
  236.          * @return this instance.
  237.          */
  238.         public Builder<K, V> setSourceMap(final Map<? extends K, ? extends V> sourceMap) {
  239.             this.sourceMap = sourceMap;
  240.             return this;
  241.         }

  242.         /**
  243.          * Sets the reference type to use for values.
  244.          *
  245.          * @param valueReferenceType the reference type to use for values.
  246.          * @return this instance.
  247.          */
  248.         public Builder<K, V> setValueReferenceType(final ReferenceType valueReferenceType) {
  249.             this.valueReferenceType = valueReferenceType;
  250.             return this;
  251.         }

  252.         /**
  253.          * Sets key reference type to {@link ReferenceType#SOFT}.
  254.          *
  255.          * @return this instance.
  256.          */
  257.         public Builder<K, V> softKeys() {
  258.             setKeyReferenceType(ReferenceType.SOFT);
  259.             return this;
  260.         }

  261.         /**
  262.          * Sets value reference type to {@link ReferenceType#SOFT}.
  263.          *
  264.          * @return this instance.
  265.          */
  266.         public Builder<K, V> softValues() {
  267.             setValueReferenceType(ReferenceType.SOFT);
  268.             return this;
  269.         }

  270.         /**
  271.          * Sets key reference type to {@link ReferenceType#STRONG}.
  272.          *
  273.          * @return this instance.
  274.          */
  275.         public Builder<K, V> strongKeys() {
  276.             setKeyReferenceType(ReferenceType.STRONG);
  277.             return this;
  278.         }

  279.         /**
  280.          * Sets value reference type to {@link ReferenceType#STRONG}.
  281.          *
  282.          * @return this instance.
  283.          */
  284.         public Builder<K, V> strongValues() {
  285.             setValueReferenceType(ReferenceType.STRONG);
  286.             return this;
  287.         }

  288.         /**
  289.          * Sets key reference type to {@link ReferenceType#WEAK}.
  290.          *
  291.          * @return this instance.
  292.          */
  293.         public Builder<K, V> weakKeys() {
  294.             setKeyReferenceType(ReferenceType.WEAK);
  295.             return this;
  296.         }

  297.         /**
  298.          * Sets value reference type to {@link ReferenceType#WEAK}.
  299.          *
  300.          * @return this instance.
  301.          */
  302.         public Builder<K, V> weakValues() {
  303.             setValueReferenceType(ReferenceType.WEAK);
  304.             return this;
  305.         }

  306.     }

  307.     /**
  308.      * The basic strategy is to subdivide the table among Segments, each of which itself is a concurrently readable hash table.
  309.      */
  310.     private final class CachedEntryIterator extends HashIterator implements Iterator<Entry<K, V>> {
  311.         private final InitializableEntry<K, V> entry = new InitializableEntry<>();

  312.         @Override
  313.         public Entry<K, V> next() {
  314.             final HashEntry<K, V> e = super.nextEntry();
  315.             return entry.init(e.key(), e.value());
  316.         }
  317.     }

  318.     private final class EntryIterator extends HashIterator implements Iterator<Entry<K, V>> {
  319.         @Override
  320.         public Entry<K, V> next() {
  321.             final HashEntry<K, V> e = super.nextEntry();
  322.             return new WriteThroughEntry(e.key(), e.value());
  323.         }
  324.     }

  325.     private final class EntrySet extends AbstractSet<Entry<K, V>> {

  326.         private final boolean cached;

  327.         private EntrySet(final boolean cached) {
  328.             this.cached = cached;
  329.         }

  330.         @Override
  331.         public void clear() {
  332.             ConcurrentReferenceHashMap.this.clear();
  333.         }

  334.         @Override
  335.         public boolean contains(final Object o) {
  336.             if (!(o instanceof Map.Entry)) {
  337.                 return false;
  338.             }
  339.             final V v = ConcurrentReferenceHashMap.this.get(((Entry<?, ?>) o).getKey());
  340.             return Objects.equals(v, ((Entry<?, ?>) o).getValue());
  341.         }

  342.         @Override
  343.         public boolean isEmpty() {
  344.             return ConcurrentReferenceHashMap.this.isEmpty();
  345.         }

  346.         @Override
  347.         public Iterator<Entry<K, V>> iterator() {
  348.             return cached ? new CachedEntryIterator() : new EntryIterator();
  349.         }

  350.         @Override
  351.         public boolean remove(final Object o) {
  352.             if (!(o instanceof Map.Entry)) {
  353.                 return false;
  354.             }
  355.             final Entry<?, ?> e = (Entry<?, ?>) o;
  356.             return ConcurrentReferenceHashMap.this.remove(e.getKey(), e.getValue());
  357.         }

  358.         @Override
  359.         public int size() {
  360.             return ConcurrentReferenceHashMap.this.size();
  361.         }
  362.     }

  363.     /**
  364.      * ConcurrentReferenceHashMap list entry. Note that this is never exported out as a user-visible Map.Entry.
  365.      * <p>
  366.      * Because the value field is volatile, not final, it is legal wrt the Java Memory Model for an unsynchronized reader to see null instead of initial value
  367.      * when read via a data race. Although a reordering leading to this is not likely to ever actually occur, the Segment.readValueUnderLock method is used as a
  368.      * backup in case a null (pre-initialized) value is ever seen in an unsynchronized access method.
  369.      * </p>
  370.      */
  371.     private static final class HashEntry<K, V> {

  372.         @SuppressWarnings("unchecked")
  373.         static <K, V> HashEntry<K, V>[] newArray(final int i) {
  374.             return new HashEntry[i];
  375.         }

  376.         private final Object keyRef;
  377.         private final int hash;
  378.         private volatile Object valueRef;
  379.         private final HashEntry<K, V> next;

  380.         HashEntry(final K key, final int hash, final HashEntry<K, V> next, final V value, final ReferenceType keyType, final ReferenceType valueType,
  381.                 final ReferenceQueue<Object> refQueue) {
  382.             this.hash = hash;
  383.             this.next = next;
  384.             this.keyRef = newKeyReference(key, keyType, refQueue);
  385.             this.valueRef = newValueReference(value, valueType, refQueue);
  386.         }

  387.         @SuppressWarnings("unchecked")
  388.         V dereferenceValue(final Object value) {
  389.             if (value instanceof KeyReference) {
  390.                 return ((Reference<V>) value).get();
  391.             }
  392.             return (V) value;
  393.         }

  394.         @SuppressWarnings("unchecked")
  395.         K key() {
  396.             if (keyRef instanceof KeyReference) {
  397.                 return ((Reference<K>) keyRef).get();
  398.             }
  399.             return (K) keyRef;
  400.         }

  401.         Object newKeyReference(final K key, final ReferenceType keyType, final ReferenceQueue<Object> refQueue) {
  402.             if (keyType == ReferenceType.WEAK) {
  403.                 return new WeakKeyReference<>(key, hash, refQueue);
  404.             }
  405.             if (keyType == ReferenceType.SOFT) {
  406.                 return new SoftKeyReference<>(key, hash, refQueue);
  407.             }

  408.             return key;
  409.         }

  410.         Object newValueReference(final V value, final ReferenceType valueType, final ReferenceQueue<Object> refQueue) {
  411.             if (valueType == ReferenceType.WEAK) {
  412.                 return new WeakValueReference<>(value, keyRef, hash, refQueue);
  413.             }
  414.             if (valueType == ReferenceType.SOFT) {
  415.                 return new SoftValueReference<>(value, keyRef, hash, refQueue);
  416.             }

  417.             return value;
  418.         }

  419.         void setValue(final V value, final ReferenceType valueType, final ReferenceQueue<Object> refQueue) {
  420.             this.valueRef = newValueReference(value, valueType, refQueue);
  421.         }

  422.         V value() {
  423.             return dereferenceValue(valueRef);
  424.         }
  425.     }

  426.     private abstract class HashIterator {
  427.         private int nextSegmentIndex;
  428.         private int nextTableIndex;
  429.         private HashEntry<K, V>[] currentTable;
  430.         private HashEntry<K, V> nextEntry;
  431.         private HashEntry<K, V> lastReturned;
  432.         // Strong reference to weak key (prevents gc)
  433.         private K currentKey;

  434.         private HashIterator() {
  435.             nextSegmentIndex = segments.length - 1;
  436.             nextTableIndex = -1;
  437.             advance();
  438.         }

  439.         final void advance() {
  440.             if (nextEntry != null && (nextEntry = nextEntry.next) != null) {
  441.                 return;
  442.             }
  443.             while (nextTableIndex >= 0) {
  444.                 if ((nextEntry = currentTable[nextTableIndex--]) != null) {
  445.                     return;
  446.                 }
  447.             }
  448.             while (nextSegmentIndex >= 0) {
  449.                 final Segment<K, V> seg = segments[nextSegmentIndex--];
  450.                 if (seg.count != 0) {
  451.                     currentTable = seg.table;
  452.                     for (int j = currentTable.length - 1; j >= 0; --j) {
  453.                         if ((nextEntry = currentTable[j]) != null) {
  454.                             nextTableIndex = j - 1;
  455.                             return;
  456.                         }
  457.                     }
  458.                 }
  459.             }
  460.         }

  461.         public boolean hasMoreElements() {
  462.             return hasNext();
  463.         }

  464.         public boolean hasNext() {
  465.             while (nextEntry != null) {
  466.                 if (nextEntry.key() != null) {
  467.                     return true;
  468.                 }
  469.                 advance();
  470.             }
  471.             return false;
  472.         }

  473.         HashEntry<K, V> nextEntry() {
  474.             do {
  475.                 if (nextEntry == null) {
  476.                     throw new NoSuchElementException();
  477.                 }
  478.                 lastReturned = nextEntry;
  479.                 currentKey = lastReturned.key();
  480.                 advance();
  481.             } while /* Skip GC'd keys */ (currentKey == null);
  482.             return lastReturned;
  483.         }

  484.         public void remove() {
  485.             if (lastReturned == null) {
  486.                 throw new IllegalStateException();
  487.             }
  488.             ConcurrentReferenceHashMap.this.remove(currentKey);
  489.             lastReturned = null;
  490.         }
  491.     }

  492.     private static final class InitializableEntry<K, V> implements Entry<K, V> {
  493.         private K key;
  494.         private V value;

  495.         @Override
  496.         public K getKey() {
  497.             return key;
  498.         }

  499.         @Override
  500.         public V getValue() {
  501.             return value;
  502.         }

  503.         public Entry<K, V> init(final K key, final V value) {
  504.             this.key = key;
  505.             this.value = value;
  506.             return this;
  507.         }

  508.         @Override
  509.         public V setValue(final V value) {
  510.             throw new UnsupportedOperationException();
  511.         }
  512.     }

  513.     private final class KeyIterator extends HashIterator implements Iterator<K>, Enumeration<K> {
  514.         @Override
  515.         public K next() {
  516.             return super.nextEntry().key();
  517.         }

  518.         @Override
  519.         public K nextElement() {
  520.             return super.nextEntry().key();
  521.         }
  522.     }

  523.     private interface KeyReference {
  524.         int keyHash();

  525.         Object keyRef();
  526.     }

  527.     private final class KeySet extends AbstractSet<K> {
  528.         @Override
  529.         public void clear() {
  530.             ConcurrentReferenceHashMap.this.clear();
  531.         }

  532.         @Override
  533.         public boolean contains(final Object o) {
  534.             return ConcurrentReferenceHashMap.this.containsKey(o);
  535.         }

  536.         @Override
  537.         public boolean isEmpty() {
  538.             return ConcurrentReferenceHashMap.this.isEmpty();
  539.         }

  540.         @Override
  541.         public Iterator<K> iterator() {
  542.             return new KeyIterator();
  543.         }

  544.         @Override
  545.         public boolean remove(final Object o) {
  546.             return ConcurrentReferenceHashMap.this.remove(o) != null;
  547.         }

  548.         @Override
  549.         public int size() {
  550.             return ConcurrentReferenceHashMap.this.size();
  551.         }
  552.     }

  553.     /**
  554.      * Behavior-changing configuration options for the map
  555.      */
  556.     public enum Option {
  557.         /**
  558.          * Indicates that referential-equality (== instead of .equals()) should be used when locating keys. This offers similar behavior to
  559.          * {@link IdentityHashMap}
  560.          */
  561.         IDENTITY_COMPARISONS
  562.     }

  563.     /**
  564.      * An option specifying which Java reference type should be used to refer to a key and/or value.
  565.      */
  566.     public enum ReferenceType {
  567.         /**
  568.          * Indicates a normal Java strong reference should be used
  569.          */
  570.         STRONG,
  571.         /**
  572.          * Indicates a {@link WeakReference} should be used
  573.          */
  574.         WEAK,
  575.         /**
  576.          * Indicates a {@link SoftReference} should be used
  577.          */
  578.         SOFT
  579.     }

  580.     /**
  581.      * Segments are specialized versions of hash tables. This subclasses from ReentrantLock opportunistically, just to simplify some locking and avoid separate
  582.      * construction.
  583.      * <p>
  584.      * Segments maintain a table of entry lists that are ALWAYS kept in a consistent state, so they can be read without locking. Next fields of nodes are
  585.      * immutable (final). All list additions are performed at the front of each bin. This makes it easy to check changes, and also fast to traverse. When nodes
  586.      * would otherwise be changed, new nodes are created to replace them. This works well for hash tables since the bin lists tend to be short. (The average
  587.      * length is less than two for the default load factor threshold.)
  588.      * </p>
  589.      * <p>
  590.      * Read operations can thus proceed without locking, but rely on selected uses of volatiles to ensure that completed write operations performed by other
  591.      * threads are noticed. For most purposes, the "count" field, tracking the number of elements, serves as that volatile variable ensuring visibility. This is
  592.      * convenient because this field needs to be read in many read operations anyway:
  593.      * </p>
  594.      * <ul>
  595.      * <li>All (unsynchronized) read operations must first read the "count" field, and should not look at table entries if it is 0.</li>
  596.      * <li>All (synchronized) write operations should write to the "count" field after structurally changing any bin. The operations must not take any action
  597.      * that could even momentarily cause a concurrent read operation to see inconsistent data. This is made easier by the nature of the read operations in Map.
  598.      * For example, no operation can reveal that the table has grown but the threshold has not yet been updated, so there are no atomicity requirements for this
  599.      * with respect to reads.</li>
  600.      * </ul>
  601.      * <p>
  602.      * As a guide, all critical volatile reads and writes to the count field are marked in code comments.
  603.      * </p>
  604.      *
  605.      * @param <K> the type of keys maintained by this Segment.
  606.      * @param <V> the type of mapped values.
  607.      */
  608.     private static final class Segment<K, V> extends ReentrantLock {

  609.         private static final long serialVersionUID = 1L;

  610.         @SuppressWarnings("unchecked")
  611.         static <K, V> Segment<K, V>[] newArray(final int i) {
  612.             return new Segment[i];
  613.         }

  614.         /**
  615.          * The number of elements in this segment's region.
  616.          */
  617.         // @SuppressFBWarnings(value = "SE_TRANSIENT_FIELD_NOT_RESTORED", justification =
  618.         // "I trust Doug Lea's technical decision")
  619.         private transient volatile int count;

  620.         /**
  621.          * Number of updates that alter the size of the table. This is used during bulk-read methods to make sure they see a consistent snapshot: If modCounts
  622.          * change during a traversal of segments computing size or checking containsValue, then we might have an inconsistent view of state so (usually) we must
  623.          * retry.
  624.          */
  625.         // @SuppressFBWarnings(value = "SE_TRANSIENT_FIELD_NOT_RESTORED", justification =
  626.         // "I trust Doug Lea's technical decision")
  627.         private transient int modCount;

  628.         /**
  629.          * The table is rehashed when its size exceeds this threshold. (The value of this field is always <code>(int)(capacity *
  630.          * loadFactor)</code>.)
  631.          */
  632.         private transient int threshold;

  633.         /**
  634.          * The per-segment table.
  635.          */
  636.         private transient volatile HashEntry<K, V>[] table;

  637.         /**
  638.          * The load factor for the hash table. Even though this value is same for all segments, it is replicated to avoid needing links to outer object.
  639.          */
  640.         private final float loadFactor;

  641.         /**
  642.          * The collected weak-key reference queue for this segment. This should be (re)initialized whenever table is assigned,
  643.          */
  644.         private transient volatile ReferenceQueue<Object> refQueue;

  645.         private final ReferenceType keyType;

  646.         private final ReferenceType valueType;

  647.         private final boolean identityComparisons;

  648.         Segment(final int initialCapacity, final float loadFactor, final ReferenceType keyType, final ReferenceType valueType,
  649.                 final boolean identityComparisons) {
  650.             this.loadFactor = loadFactor;
  651.             this.keyType = keyType;
  652.             this.valueType = valueType;
  653.             this.identityComparisons = identityComparisons;
  654.             setTable(HashEntry.<K, V>newArray(initialCapacity));
  655.         }

  656.         V apply(final K key, final int hash, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  657.             lock();
  658.             try {
  659.                 final V oldValue = get(key, hash);
  660.                 final V newValue = remappingFunction.apply(key, oldValue);

  661.                 if (newValue == null) {
  662.                     // delete mapping
  663.                     if (oldValue != null) {
  664.                         // something to remove
  665.                         removeInternal(key, hash, oldValue, false);
  666.                     }
  667.                     return null;
  668.                 }
  669.                 // add or replace old mapping
  670.                 putInternal(key, hash, newValue, null, false);
  671.                 return newValue;
  672.             } finally {
  673.                 unlock();
  674.             }
  675.         }

  676.         V applyIfPresent(final K key, final int hash, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  677.             lock();
  678.             try {
  679.                 final V oldValue = get(key, hash);
  680.                 if (oldValue == null) {
  681.                     return null;
  682.                 }

  683.                 final V newValue = remappingFunction.apply(key, oldValue);

  684.                 if (newValue == null) {
  685.                     removeInternal(key, hash, oldValue, false);
  686.                     return null;
  687.                 }
  688.                 putInternal(key, hash, newValue, null, false);
  689.                 return newValue;
  690.             } finally {
  691.                 unlock();
  692.             }
  693.         }

  694.         void clear() {
  695.             if (count != 0) {
  696.                 lock();
  697.                 try {
  698.                     final HashEntry<K, V>[] tab = table;
  699.                     Arrays.fill(tab, null);
  700.                     ++modCount;
  701.                     // replace the reference queue to avoid unnecessary stale cleanups
  702.                     refQueue = new ReferenceQueue<>();
  703.                     // write-volatile
  704.                     count = 0;
  705.                 } finally {
  706.                     unlock();
  707.                 }
  708.             }
  709.         }

  710.         boolean containsKey(final Object key, final int hash) {
  711.             // read-volatile
  712.             if (count != 0) {
  713.                 HashEntry<K, V> e = getFirst(hash);
  714.                 while (e != null) {
  715.                     if (e.hash == hash && keyEq(key, e.key())) {
  716.                         return true;
  717.                     }
  718.                     e = e.next;
  719.                 }
  720.             }
  721.             return false;
  722.         }

  723.         boolean containsValue(final Object value) {
  724.             // read-volatile
  725.             if (count != 0) {
  726.                 final HashEntry<K, V>[] tab = table;
  727.                 final int len = tab.length;
  728.                 for (int i = 0; i < len; i++) {
  729.                     for (HashEntry<K, V> e = tab[i]; e != null; e = e.next) {
  730.                         final Object opaque = e.valueRef;
  731.                         final V v;
  732.                         if (opaque == null) {
  733.                             // recheck
  734.                             v = readValueUnderLock(e);
  735.                         } else {
  736.                             v = e.dereferenceValue(opaque);
  737.                         }
  738.                         if (Objects.equals(value, v)) {
  739.                             return true;
  740.                         }
  741.                     }
  742.                 }
  743.             }
  744.             return false;
  745.         }

  746.         /* Specialized implementations of map methods */
  747.         V get(final Object key, final int hash) {
  748.             // read-volatile
  749.             if (count != 0) {
  750.                 HashEntry<K, V> e = getFirst(hash);
  751.                 while (e != null) {
  752.                     if (e.hash == hash && keyEq(key, e.key())) {
  753.                         final Object opaque = e.valueRef;
  754.                         if (opaque != null) {
  755.                             return e.dereferenceValue(opaque);
  756.                         }
  757.                         // recheck
  758.                         return readValueUnderLock(e);
  759.                     }
  760.                     e = e.next;
  761.                 }
  762.             }
  763.             return null;
  764.         }

  765.         /**
  766.          * Gets properly casted first entry of bin for given hash.
  767.          */
  768.         HashEntry<K, V> getFirst(final int hash) {
  769.             final HashEntry<K, V>[] tab = table;
  770.             return tab[hash & tab.length - 1];
  771.         }

  772.         V getValue(final K key, final V value, final Function<? super K, ? extends V> function) {
  773.             return value != null ? value : function.apply(key);
  774.         }

  775.         private boolean keyEq(final Object src, final Object dest) {
  776.             return identityComparisons ? src == dest : Objects.equals(src, dest);
  777.         }

  778.         HashEntry<K, V> newHashEntry(final K key, final int hash, final HashEntry<K, V> next, final V value) {
  779.             return new HashEntry<>(key, hash, next, value, keyType, valueType, refQueue);
  780.         }

  781.         /**
  782.          * This method must be called with exactly one of <code>value</code> and <code>function</code> non-null.
  783.          **/
  784.         V put(final K key, final int hash, final V value, final Function<? super K, ? extends V> function, final boolean onlyIfAbsent) {
  785.             lock();
  786.             try {
  787.                 return putInternal(key, hash, value, function, onlyIfAbsent);
  788.             } finally {
  789.                 unlock();
  790.             }
  791.         }

  792.         private V putInternal(final K key, final int hash, final V value, final Function<? super K, ? extends V> function, final boolean onlyIfAbsent) {
  793.             removeStale();
  794.             int c = count;
  795.             // ensure capacity
  796.             if (c++ > threshold) {
  797.                 final int reduced = rehash();
  798.                 // adjust from possible weak cleanups
  799.                 if (reduced > 0) {
  800.                     // write-volatile
  801.                     count = (c -= reduced) - 1;
  802.                 }
  803.             }
  804.             final HashEntry<K, V>[] tab = table;
  805.             final int index = hash & tab.length - 1;
  806.             final HashEntry<K, V> first = tab[index];
  807.             HashEntry<K, V> e = first;
  808.             while (e != null && (e.hash != hash || !keyEq(key, e.key()))) {
  809.                 e = e.next;
  810.             }
  811.             final V resultValue;
  812.             if (e != null) {
  813.                 resultValue = e.value();
  814.                 if (!onlyIfAbsent) {
  815.                     e.setValue(getValue(key, value, function), valueType, refQueue);
  816.                 }
  817.             } else {
  818.                 final V v = getValue(key, value, function);
  819.                 resultValue = function != null ? v : null;

  820.                 if (v != null) {
  821.                     ++modCount;
  822.                     tab[index] = newHashEntry(key, hash, first, v);
  823.                     // write-volatile
  824.                     count = c;
  825.                 }
  826.             }
  827.             return resultValue;
  828.         }

  829.         /**
  830.          * Reads value field of an entry under lock. Called if value field ever appears to be null. This is possible only if a compiler happens to reorder a
  831.          * HashEntry initialization with its table assignment, which is legal under memory model but is not known to ever occur.
  832.          */
  833.         V readValueUnderLock(final HashEntry<K, V> e) {
  834.             lock();
  835.             try {
  836.                 removeStale();
  837.                 return e.value();
  838.             } finally {
  839.                 unlock();
  840.             }
  841.         }

  842.         int rehash() {
  843.             final HashEntry<K, V>[] oldTable = table;
  844.             final int oldCapacity = oldTable.length;
  845.             if (oldCapacity >= MAXIMUM_CAPACITY) {
  846.                 return 0;
  847.             }
  848.             //
  849.             // Reclassify nodes in each list to new Map. Because we are using power-of-two expansion, the elements from each bin must either stay at the same
  850.             // index, or move with a power of two offset. We eliminate unnecessary node creation by catching cases where old nodes can be reused because their
  851.             // next fields won't change. Statistically, at the default threshold, only about one-sixth of them need cloning when a table doubles. The nodes they
  852.             // replace will be garbage collectable as soon as they are no longer referenced by any reader thread that may be in the midst of traversing table
  853.             // right now.
  854.             //
  855.             final HashEntry<K, V>[] newTable = HashEntry.newArray(oldCapacity << 1);
  856.             threshold = (int) (newTable.length * loadFactor);
  857.             final int sizeMask = newTable.length - 1;
  858.             int reduce = 0;
  859.             for (int i = 0; i < oldCapacity; i++) {
  860.                 // We need to guarantee that any existing reads of old Map can
  861.                 // proceed. So we cannot yet null out each bin.
  862.                 final HashEntry<K, V> e = oldTable[i];
  863.                 if (e != null) {
  864.                     final HashEntry<K, V> next = e.next;
  865.                     final int idx = e.hash & sizeMask;
  866.                     // Single node on list
  867.                     if (next == null) {
  868.                         newTable[idx] = e;
  869.                     } else {
  870.                         // Reuse trailing consecutive sequence at same slot
  871.                         HashEntry<K, V> lastRun = e;
  872.                         int lastIdx = idx;
  873.                         for (HashEntry<K, V> last = next; last != null; last = last.next) {
  874.                             final int k = last.hash & sizeMask;
  875.                             if (k != lastIdx) {
  876.                                 lastIdx = k;
  877.                                 lastRun = last;
  878.                             }
  879.                         }
  880.                         newTable[lastIdx] = lastRun;
  881.                         // Clone all remaining nodes
  882.                         for (HashEntry<K, V> p = e; p != lastRun; p = p.next) {
  883.                             // Skip GC'd weak refs
  884.                             final K key = p.key();
  885.                             if (key == null) {
  886.                                 reduce++;
  887.                                 continue;
  888.                             }
  889.                             final int k = p.hash & sizeMask;
  890.                             final HashEntry<K, V> n = newTable[k];
  891.                             newTable[k] = newHashEntry(key, p.hash, n, p.value());
  892.                         }
  893.                     }
  894.                 }
  895.             }
  896.             table = newTable;
  897.             return reduce;
  898.         }

  899.         /**
  900.          * Removes match on key only if value is null, else match both.
  901.          */
  902.         V remove(final Object key, final int hash, final Object value, final boolean refRemove) {
  903.             lock();
  904.             try {
  905.                 return removeInternal(key, hash, value, refRemove);
  906.             } finally {
  907.                 unlock();
  908.             }
  909.         }

  910.         private V removeInternal(final Object key, final int hash, final Object value, final boolean refRemove) {
  911.             if (!refRemove) {
  912.                 removeStale();
  913.             }
  914.             int c = count - 1;
  915.             final HashEntry<K, V>[] tab = table;
  916.             final int index = hash & tab.length - 1;
  917.             final HashEntry<K, V> first = tab[index];
  918.             HashEntry<K, V> e = first;
  919.             // a ref remove operation compares the Reference instance
  920.             while (e != null && key != e.keyRef && (refRemove || hash != e.hash || !keyEq(key, e.key()))) {
  921.                 e = e.next;
  922.             }

  923.             V oldValue = null;
  924.             if (e != null) {
  925.                 final V v = e.value();
  926.                 if (value == null || value.equals(v)) {
  927.                     oldValue = v;
  928.                     // All entries following removed node can stay
  929.                     // in list, but all preceding ones need to be
  930.                     // cloned.
  931.                     ++modCount;
  932.                     HashEntry<K, V> newFirst = e.next;
  933.                     for (HashEntry<K, V> p = first; p != e; p = p.next) {
  934.                         final K pKey = p.key();
  935.                         // Skip GC'd keys
  936.                         if (pKey == null) {
  937.                             c--;
  938.                             continue;
  939.                         }
  940.                         newFirst = newHashEntry(pKey, p.hash, newFirst, p.value());
  941.                     }
  942.                     tab[index] = newFirst;
  943.                     // write-volatile
  944.                     count = c;
  945.                 }
  946.             }
  947.             return oldValue;
  948.         }

  949.         void removeStale() {
  950.             KeyReference ref;
  951.             while ((ref = (KeyReference) refQueue.poll()) != null) {
  952.                 remove(ref.keyRef(), ref.keyHash(), null, true);
  953.             }
  954.         }

  955.         V replace(final K key, final int hash, final V newValue) {
  956.             lock();
  957.             try {
  958.                 return replaceInternal(key, hash, newValue);
  959.             } finally {
  960.                 unlock();
  961.             }
  962.         }

  963.         boolean replace(final K key, final int hash, final V oldValue, final V newValue) {
  964.             lock();
  965.             try {
  966.                 return replaceInternal2(key, hash, oldValue, newValue);
  967.             } finally {
  968.                 unlock();
  969.             }
  970.         }

  971.         private V replaceInternal(final K key, final int hash, final V newValue) {
  972.             removeStale();
  973.             HashEntry<K, V> e = getFirst(hash);
  974.             while (e != null && (e.hash != hash || !keyEq(key, e.key()))) {
  975.                 e = e.next;
  976.             }
  977.             V oldValue = null;
  978.             if (e != null) {
  979.                 oldValue = e.value();
  980.                 e.setValue(newValue, valueType, refQueue);
  981.             }
  982.             return oldValue;
  983.         }

  984.         private boolean replaceInternal2(final K key, final int hash, final V oldValue, final V newValue) {
  985.             removeStale();
  986.             HashEntry<K, V> e = getFirst(hash);
  987.             while (e != null && (e.hash != hash || !keyEq(key, e.key()))) {
  988.                 e = e.next;
  989.             }
  990.             boolean replaced = false;
  991.             if (e != null && Objects.equals(oldValue, e.value())) {
  992.                 replaced = true;
  993.                 e.setValue(newValue, valueType, refQueue);
  994.             }
  995.             return replaced;
  996.         }

  997.         /**
  998.          * Sets table to new HashEntry array. Call only while holding lock or in constructor.
  999.          */
  1000.         void setTable(final HashEntry<K, V>[] newTable) {
  1001.             threshold = (int) (newTable.length * loadFactor);
  1002.             table = newTable;
  1003.             refQueue = new ReferenceQueue<>();
  1004.         }
  1005.     }

  1006.     private static class SimpleEntry<K, V> implements Entry<K, V> {

  1007.         private static boolean eq(final Object o1, final Object o2) {
  1008.             return Objects.equals(o1, o2);
  1009.         }

  1010.         private final K key;

  1011.         private V value;

  1012.         SimpleEntry(final K key, final V value) {
  1013.             this.key = key;
  1014.             this.value = value;
  1015.         }

  1016.         @Override
  1017.         public boolean equals(final Object o) {
  1018.             if (!(o instanceof Map.Entry)) {
  1019.                 return false;
  1020.             }
  1021.             final Entry<?, ?> e = (Entry<?, ?>) o;
  1022.             return eq(key, e.getKey()) && eq(value, e.getValue());
  1023.         }

  1024.         @Override
  1025.         public K getKey() {
  1026.             return key;
  1027.         }

  1028.         @Override
  1029.         public V getValue() {
  1030.             return value;
  1031.         }

  1032.         @Override
  1033.         public int hashCode() {
  1034.             return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
  1035.         }

  1036.         @Override
  1037.         public V setValue(final V value) {
  1038.             final V oldValue = this.value;
  1039.             this.value = value;
  1040.             return oldValue;
  1041.         }

  1042.         @Override
  1043.         public String toString() {
  1044.             return key + "=" + value;
  1045.         }
  1046.     }

  1047.     /**
  1048.      * A soft-key reference which stores the key hash needed for reclamation.
  1049.      */
  1050.     private static final class SoftKeyReference<K> extends SoftReference<K> implements KeyReference {

  1051.         private final int hash;

  1052.         SoftKeyReference(final K key, final int hash, final ReferenceQueue<Object> refQueue) {
  1053.             super(key, refQueue);
  1054.             this.hash = hash;
  1055.         }

  1056.         @Override
  1057.         public int keyHash() {
  1058.             return hash;
  1059.         }

  1060.         @Override
  1061.         public Object keyRef() {
  1062.             return this;
  1063.         }
  1064.     }

  1065.     private static final class SoftValueReference<V> extends SoftReference<V> implements KeyReference {
  1066.         private final Object keyRef;
  1067.         private final int hash;

  1068.         SoftValueReference(final V value, final Object keyRef, final int hash, final ReferenceQueue<Object> refQueue) {
  1069.             super(value, refQueue);
  1070.             this.keyRef = keyRef;
  1071.             this.hash = hash;
  1072.         }

  1073.         @Override
  1074.         public int keyHash() {
  1075.             return hash;
  1076.         }

  1077.         @Override
  1078.         public Object keyRef() {
  1079.             return keyRef;
  1080.         }
  1081.     }

  1082.     private final class ValueIterator extends HashIterator implements Iterator<V>, Enumeration<V> {
  1083.         @Override
  1084.         public V next() {
  1085.             return super.nextEntry().value();
  1086.         }

  1087.         @Override
  1088.         public V nextElement() {
  1089.             return super.nextEntry().value();
  1090.         }
  1091.     }

  1092.     private final class Values extends AbstractCollection<V> {
  1093.         @Override
  1094.         public void clear() {
  1095.             ConcurrentReferenceHashMap.this.clear();
  1096.         }

  1097.         @Override
  1098.         public boolean contains(final Object o) {
  1099.             return ConcurrentReferenceHashMap.this.containsValue(o);
  1100.         }

  1101.         @Override
  1102.         public boolean isEmpty() {
  1103.             return ConcurrentReferenceHashMap.this.isEmpty();
  1104.         }

  1105.         @Override
  1106.         public Iterator<V> iterator() {
  1107.             return new ValueIterator();
  1108.         }

  1109.         @Override
  1110.         public int size() {
  1111.             return ConcurrentReferenceHashMap.this.size();
  1112.         }
  1113.     }

  1114.     /**
  1115.      * A weak-key reference which stores the key hash needed for reclamation.
  1116.      */
  1117.     private static final class WeakKeyReference<K> extends WeakReference<K> implements KeyReference {
  1118.         private final int hash;

  1119.         WeakKeyReference(final K key, final int hash, final ReferenceQueue<Object> refQueue) {
  1120.             super(key, refQueue);
  1121.             this.hash = hash;
  1122.         }

  1123.         @Override
  1124.         public int keyHash() {
  1125.             return hash;
  1126.         }

  1127.         @Override
  1128.         public Object keyRef() {
  1129.             return this;
  1130.         }
  1131.     }

  1132.     private static final class WeakValueReference<V> extends WeakReference<V> implements KeyReference {
  1133.         private final Object keyRef;
  1134.         private final int hash;

  1135.         WeakValueReference(final V value, final Object keyRef, final int hash, final ReferenceQueue<Object> refQueue) {
  1136.             super(value, refQueue);
  1137.             this.keyRef = keyRef;
  1138.             this.hash = hash;
  1139.         }

  1140.         @Override
  1141.         public int keyHash() {
  1142.             return hash;
  1143.         }

  1144.         @Override
  1145.         public Object keyRef() {
  1146.             return keyRef;
  1147.         }
  1148.     }

  1149.     /**
  1150.      * Custom Entry class used by EntryIterator.next(), that relays setValue changes to the underlying map.
  1151.      */
  1152.     private final class WriteThroughEntry extends SimpleEntry<K, V> {

  1153.         private WriteThroughEntry(final K k, final V v) {
  1154.             super(k, v);
  1155.         }

  1156.         /**
  1157.          * Set our entry's value and writes it through to the map. The value to return is somewhat arbitrary: since a WriteThroughEntry does not necessarily
  1158.          * track asynchronous changes, the most recent "previous" value could be different from what we return (or could even have been removed in which case
  1159.          * the put will re-establish). We do not and cannot guarantee more.
  1160.          */
  1161.         @Override
  1162.         public V setValue(final V value) {
  1163.             Objects.requireNonNull(value, "value");
  1164.             final V v = super.setValue(value);
  1165.             ConcurrentReferenceHashMap.this.put(getKey(), value);
  1166.             return v;
  1167.         }
  1168.     }

  1169.     static final ReferenceType DEFAULT_KEY_TYPE = ReferenceType.WEAK;

  1170.     static final ReferenceType DEFAULT_VALUE_TYPE = ReferenceType.STRONG;

  1171.     static final EnumSet<Option> DEFAULT_OPTIONS = null;

  1172.     /**
  1173.      * The default initial capacity for this table, used when not otherwise specified in a constructor.
  1174.      */
  1175.     static final int DEFAULT_INITIAL_CAPACITY = 16;

  1176.     /**
  1177.      * The default load factor for this table, used when not otherwise specified in a constructor.
  1178.      */
  1179.     static final float DEFAULT_LOAD_FACTOR = 0.75f;

  1180.     /**
  1181.      * The default concurrency level for this table, used when not otherwise specified in a constructor.
  1182.      */
  1183.     static final int DEFAULT_CONCURRENCY_LEVEL = 16;

  1184.     /**
  1185.      * The maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments. MUST be a power of two &lt;=
  1186.      * 1&lt;&lt;30 to ensure that entries are indexable using ints.
  1187.      */
  1188.     private static final int MAXIMUM_CAPACITY = 1 << 30;

  1189.     /**
  1190.      * The maximum number of segments to allow; used to bound constructor arguments.
  1191.      */
  1192.     private static final int MAX_SEGMENTS = 1 << 16;

  1193.     /**
  1194.      * Number of unsynchronized retries in size and containsValue methods before resorting to locking. This is used to avoid unbounded retries if tables undergo
  1195.      * continuous modification which would make it impossible to obtain an accurate result.
  1196.      */
  1197.     private static final int RETRIES_BEFORE_LOCK = 2;

  1198.     /**
  1199.      * Creates a new Builder.
  1200.      * <p>
  1201.      * By default, keys are weak, and values are strong.
  1202.      * </p>
  1203.      * <p>
  1204.      * The default values are:
  1205.      * </p>
  1206.      * <ul>
  1207.      * <li>concurrency level: {@value #DEFAULT_CONCURRENCY_LEVEL}</li>
  1208.      * <li>initial capacity: {@value #DEFAULT_INITIAL_CAPACITY}</li>
  1209.      * <li>key reference type: {@link ReferenceType#WEAK}</li>
  1210.      * <li>load factor: {@value #DEFAULT_LOAD_FACTOR}</li>
  1211.      * <li>options: {@code null}</li>
  1212.      * <li>source map: {@code null}</li>
  1213.      * <li>value reference type: {@link ReferenceType#STRONG}</li>
  1214.      * </ul>
  1215.      *
  1216.      * @param <K> the type of keys.
  1217.      * @param <V> the type of values.
  1218.      * @return a new Builder.
  1219.      */
  1220.     public static <K, V> Builder<K, V> builder() {
  1221.         return new Builder<>();
  1222.     }

  1223.     /**
  1224.      * Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions. This is critical because
  1225.      * ConcurrentReferenceHashMap uses power-of-two length hash tables, that otherwise encounter collisions for hashCodes that do not differ in lower or upper
  1226.      * bits.
  1227.      */
  1228.     private static int hash(int h) {
  1229.         // Spread bits to regularize both segment and index locations,
  1230.         // using variant of single-word Wang/Jenkins hash.
  1231.         h += h << 15 ^ 0xffffcd7d;
  1232.         h ^= h >>> 10;
  1233.         h += h << 3;
  1234.         h ^= h >>> 6;
  1235.         h += (h << 2) + (h << 14);
  1236.         return h ^ h >>> 16;
  1237.     }

  1238.     /**
  1239.      * Mask value for indexing into segments. The upper bits of a key's hash code are used to choose the segment.
  1240.      */
  1241.     private final int segmentMask;

  1242.     /**
  1243.      * Shift value for indexing within segments.
  1244.      */
  1245.     private final int segmentShift;

  1246.     /**
  1247.      * The segments, each of which is a specialized hash table
  1248.      */
  1249.     private final Segment<K, V>[] segments;

  1250.     private final boolean identityComparisons;

  1251.     private transient Set<K> keySet;

  1252.     private transient Set<Entry<K, V>> entrySet;

  1253.     private transient Collection<V> values;

  1254.     /**
  1255.      * Creates a new, empty map with the specified initial capacity, reference types, load factor, and concurrency level.
  1256.      * <p>
  1257.      * Behavioral changing options such as {@link Option#IDENTITY_COMPARISONS} can also be specified.
  1258.      * </p>
  1259.      *
  1260.      * @param initialCapacity  the initial capacity. The implementation performs internal sizing to accommodate this many elements.
  1261.      * @param loadFactor       the load factor threshold, used to control resizing. Resizing may be performed when the average number of elements per bin
  1262.      *                         exceeds this threshold.
  1263.      * @param concurrencyLevel the estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this
  1264.      *                         many threads.
  1265.      * @param keyType          the reference type to use for keys.
  1266.      * @param valueType        the reference type to use for values.
  1267.      * @param options          the behavioral options.
  1268.      * @throws IllegalArgumentException if the initial capacity is negative or the load factor or concurrencyLevel are nonpositive.
  1269.      */
  1270.     private ConcurrentReferenceHashMap(int initialCapacity, final float loadFactor, int concurrencyLevel, final ReferenceType keyType,
  1271.             final ReferenceType valueType, final EnumSet<Option> options) {
  1272.         if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0) {
  1273.             throw new IllegalArgumentException();
  1274.         }
  1275.         if (concurrencyLevel > MAX_SEGMENTS) {
  1276.             concurrencyLevel = MAX_SEGMENTS;
  1277.         }
  1278.         // Find power-of-two sizes best matching arguments
  1279.         int sshift = 0;
  1280.         int ssize = 1;
  1281.         while (ssize < concurrencyLevel) {
  1282.             ++sshift;
  1283.             ssize <<= 1;
  1284.         }
  1285.         segmentShift = 32 - sshift;
  1286.         segmentMask = ssize - 1;
  1287.         this.segments = Segment.newArray(ssize);
  1288.         if (initialCapacity > MAXIMUM_CAPACITY) {
  1289.             initialCapacity = MAXIMUM_CAPACITY;
  1290.         }
  1291.         int c = initialCapacity / ssize;
  1292.         if (c * ssize < initialCapacity) {
  1293.             ++c;
  1294.         }
  1295.         int cap = 1;
  1296.         while (cap < c) {
  1297.             cap <<= 1;
  1298.         }
  1299.         identityComparisons = options != null && options.contains(Option.IDENTITY_COMPARISONS);
  1300.         for (int i = 0; i < this.segments.length; ++i) {
  1301.             this.segments[i] = new Segment<>(cap, loadFactor, keyType, valueType, identityComparisons);
  1302.         }
  1303.     }

  1304.     /**
  1305.      * Removes all of the mappings from this map.
  1306.      */
  1307.     @Override
  1308.     public void clear() {
  1309.         for (final Segment<K, V> segment : segments) {
  1310.             segment.clear();
  1311.         }
  1312.     }

  1313.     @Override
  1314.     public V compute(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  1315.         Objects.requireNonNull(key);
  1316.         Objects.requireNonNull(remappingFunction);

  1317.         final int hash = hashOf(key);
  1318.         final Segment<K, V> segment = segmentFor(hash);
  1319.         return segment.apply(key, hash, remappingFunction);
  1320.     }

  1321.     /**
  1322.      * The default implementation is equivalent to the following steps for this {@code map}, then returning the current value or {@code null} if now absent:
  1323.      *
  1324.      * <pre>{@code
  1325.      * if (map.get(key) == null) {
  1326.      *     V newValue = mappingFunction.apply(key);
  1327.      *     if (newValue != null)
  1328.      *         return map.putIfAbsent(key, newValue);
  1329.      * }
  1330.      * }</pre>
  1331.      * <p>
  1332.      * The default implementation may retry these steps when multiple threads attempt updates including potentially calling the mapping function multiple times.
  1333.      * </p>
  1334.      * <p>
  1335.      * This implementation assumes that the ConcurrentMap cannot contain null values and {@code get()} returning null unambiguously means the key is absent.
  1336.      * Implementations which support null values <strong>must</strong> override this default implementation.
  1337.      * </p>
  1338.      */
  1339.     @Override
  1340.     public V computeIfAbsent(final K key, final Function<? super K, ? extends V> mappingFunction) {
  1341.         Objects.requireNonNull(key);
  1342.         Objects.requireNonNull(mappingFunction);

  1343.         final int hash = hashOf(key);
  1344.         final Segment<K, V> segment = segmentFor(hash);
  1345.         final V v = segment.get(key, hash);
  1346.         return v == null ? segment.put(key, hash, null, mappingFunction, true) : v;
  1347.     }

  1348.     @Override
  1349.     public V computeIfPresent(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  1350.         Objects.requireNonNull(key);
  1351.         Objects.requireNonNull(remappingFunction);

  1352.         final int hash = hashOf(key);
  1353.         final Segment<K, V> segment = segmentFor(hash);
  1354.         final V v = segment.get(key, hash);
  1355.         if (v == null) {
  1356.             return null;
  1357.         }

  1358.         return segmentFor(hash).applyIfPresent(key, hash, remappingFunction);
  1359.     }

  1360.     /**
  1361.      * Tests if the specified object is a key in this table.
  1362.      *
  1363.      * @param key possible key
  1364.      * @return {@code true} if and only if the specified object is a key in this table, as determined by the {@code equals} method; {@code false} otherwise.
  1365.      * @throws NullPointerException if the specified key is null
  1366.      */
  1367.     @Override
  1368.     public boolean containsKey(final Object key) {
  1369.         final int hash = hashOf(key);
  1370.         return segmentFor(hash).containsKey(key, hash);
  1371.     }

  1372.     /**
  1373.      * Returns {@code true} if this map maps one or more keys to the specified value. Note: This method requires a full internal traversal of the hash table,
  1374.      * therefore it is much slower than the method {@code containsKey}.
  1375.      *
  1376.      * @param value value whose presence in this map is to be tested
  1377.      * @return {@code true} if this map maps one or more keys to the specified value
  1378.      * @throws NullPointerException if the specified value is null
  1379.      */
  1380.     @Override
  1381.     public boolean containsValue(final Object value) {
  1382.         Objects.requireNonNull(value, "value");
  1383.         // See explanation of modCount use above
  1384.         final Segment<K, V>[] segments = this.segments;
  1385.         final int[] mc = new int[segments.length];
  1386.         // Try a few times without locking
  1387.         for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
  1388.             // final int sum = 0;
  1389.             int mcsum = 0;
  1390.             for (int i = 0; i < segments.length; ++i) {
  1391.                 // final int c = segments[i].count;
  1392.                 mcsum += mc[i] = segments[i].modCount;
  1393.                 if (segments[i].containsValue(value)) {
  1394.                     return true;
  1395.                 }
  1396.             }
  1397.             boolean cleanSweep = true;
  1398.             if (mcsum != 0) {
  1399.                 for (int i = 0; i < segments.length; ++i) {
  1400.                     // final int c = segments[i].count;
  1401.                     if (mc[i] != segments[i].modCount) {
  1402.                         cleanSweep = false;
  1403.                         break;
  1404.                     }
  1405.                 }
  1406.             }
  1407.             if (cleanSweep) {
  1408.                 return false;
  1409.             }
  1410.         }
  1411.         // Resort to locking all segments
  1412.         for (final Segment<K, V> segment : segments) {
  1413.             segment.lock();
  1414.         }
  1415.         boolean found = false;
  1416.         try {
  1417.             for (final Segment<K, V> segment : segments) {
  1418.                 if (segment.containsValue(value)) {
  1419.                     found = true;
  1420.                     break;
  1421.                 }
  1422.             }
  1423.         } finally {
  1424.             for (final Segment<K, V> segment : segments) {
  1425.                 segment.unlock();
  1426.             }
  1427.         }
  1428.         return found;
  1429.     }

  1430.     /**
  1431.      * Returns a {@link Set} view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and
  1432.      * vice-versa. The set supports element removal, which removes the corresponding mapping from the map, via the {@code Iterator.remove}, {@code Set.remove},
  1433.      * {@code removeAll}, {@code retainAll}, and {@code clear} operations. It does not support the {@code add} or {@code addAll} operations.
  1434.      * <p>
  1435.      * The view's {@code iterator} is a "weakly consistent" iterator that will never throw {@link ConcurrentModificationException}, and is guaranteed to
  1436.      * traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to
  1437.      * construction.
  1438.      * </p>
  1439.      */
  1440.     @Override
  1441.     public Set<Entry<K, V>> entrySet() {
  1442.         final Set<Entry<K, V>> es = entrySet;
  1443.         return es != null ? es : (entrySet = new EntrySet(false));
  1444.     }

  1445.     /**
  1446.      * Gets the value to which the specified key is mapped, or {@code null} if this map contains no mapping for the key.
  1447.      * <p>
  1448.      * If this map contains a mapping from a key {@code k} to a value {@code v} such that {@code key.equals(k)}, then this method returns {@code v}; otherwise
  1449.      * it returns {@code null}. (There can be at most one such mapping.)
  1450.      * </p>
  1451.      *
  1452.      * @throws NullPointerException if the specified key is null
  1453.      */
  1454.     @Override
  1455.     public V get(final Object key) {
  1456.         final int hash = hashOf(key);
  1457.         return segmentFor(hash).get(key, hash);
  1458.     }

  1459.     private int hashOf(final Object key) {
  1460.         return hash(identityComparisons ? System.identityHashCode(key) : key.hashCode());
  1461.     }

  1462.     /**
  1463.      * Returns {@code true} if this map contains no key-value mappings.
  1464.      *
  1465.      * @return {@code true} if this map contains no key-value mappings
  1466.      */
  1467.     @Override
  1468.     public boolean isEmpty() {
  1469.         final Segment<K, V>[] segments = this.segments;
  1470.         //
  1471.         // We keep track of per-segment modCounts to avoid ABA problems in which an element in one segment was added and in another removed during traversal, in
  1472.         // which case the table was never actually empty at any point. Note the similar use of modCounts in the size() and containsValue() methods, which are
  1473.         // the only other methods also susceptible to ABA problems.
  1474.         //
  1475.         final int[] mc = new int[segments.length];
  1476.         int mcsum = 0;
  1477.         for (int i = 0; i < segments.length; ++i) {
  1478.             if (segments[i].count != 0) {
  1479.                 return false;
  1480.             }
  1481.             mcsum += mc[i] = segments[i].modCount;
  1482.         }
  1483.         // If mcsum happens to be zero, then we know we got a snapshot
  1484.         // before any modifications at all were made. This is
  1485.         // probably common enough to bother tracking.
  1486.         if (mcsum != 0) {
  1487.             for (int i = 0; i < segments.length; ++i) {
  1488.                 if (segments[i].count != 0 || mc[i] != segments[i].modCount) {
  1489.                     return false;
  1490.                 }
  1491.             }
  1492.         }
  1493.         return true;
  1494.     }

  1495.     /**
  1496.      * Returns a {@link Set} view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and
  1497.      * vice-versa. The set supports element removal, which removes the corresponding mapping from this map, via the {@code Iterator.remove}, {@code Set.remove},
  1498.      * {@code removeAll}, {@code retainAll}, and {@code clear} operations. It does not support the {@code add} or {@code addAll} operations.
  1499.      * <p>
  1500.      * The view's {@code iterator} is a "weakly consistent" iterator that will never throw {@link ConcurrentModificationException}, and guarantees to traverse
  1501.      * elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.
  1502.      * </p>
  1503.      */
  1504.     @Override
  1505.     public Set<K> keySet() {
  1506.         final Set<K> ks = keySet;
  1507.         return ks != null ? ks : (keySet = new KeySet());
  1508.     }

  1509.     /**
  1510.      * Removes any stale entries whose keys have been finalized. Use of this method is normally not necessary since stale entries are automatically removed
  1511.      * lazily, when blocking operations are required. However, there are some cases where this operation should be performed eagerly, such as cleaning up old
  1512.      * references to a ClassLoader in a multi-classloader environment.
  1513.      * <p>
  1514.      * Note: this method will acquire locks one at a time across all segments of this table, so this method should be used sparingly.
  1515.      * </p>
  1516.      */
  1517.     public void purgeStaleEntries() {
  1518.         for (final Segment<K, V> segment : segments) {
  1519.             segment.removeStale();
  1520.         }
  1521.     }

  1522.     /**
  1523.      * Maps the specified key to the specified value in this table. Neither the key nor the value can be null.
  1524.      * <p>
  1525.      * The value can be retrieved by calling the {@code get} method with a key that is equal to the original key.
  1526.      * </p>
  1527.      *
  1528.      * @param key   key with which the specified value is to be associated
  1529.      * @param value value to be associated with the specified key
  1530.      * @return the previous value associated with {@code key}, or {@code null} if there was no mapping for {@code key}
  1531.      * @throws NullPointerException if the specified key or value is null
  1532.      */
  1533.     @Override
  1534.     public V put(final K key, final V value) {
  1535.         Objects.requireNonNull(key, "key");
  1536.         Objects.requireNonNull(value, "value");
  1537.         final int hash = hashOf(key);
  1538.         return segmentFor(hash).put(key, hash, value, null, false);
  1539.     }

  1540.     /**
  1541.      * Copies all of the mappings from the specified map to this one. These mappings replace any mappings that this map had for any of the keys currently in the
  1542.      * specified map.
  1543.      *
  1544.      * @param m mappings to be stored in this map
  1545.      */
  1546.     @Override
  1547.     public void putAll(final Map<? extends K, ? extends V> m) {
  1548.         for (final Entry<? extends K, ? extends V> e : m.entrySet()) {
  1549.             put(e.getKey(), e.getValue());
  1550.         }
  1551.     }

  1552.     /**
  1553.      * {@inheritDoc}
  1554.      *
  1555.      * @return the previous value associated with the specified key, or {@code null} if there was no mapping for the key
  1556.      * @throws NullPointerException if the specified key or value is null
  1557.      */
  1558.     @Override
  1559.     public V putIfAbsent(final K key, final V value) {
  1560.         Objects.requireNonNull(value, "value");
  1561.         final int hash = hashOf(key);
  1562.         return segmentFor(hash).put(key, hash, value, null, true);
  1563.     }

  1564.     /**
  1565.      * Removes the key (and its corresponding value) from this map. This method does nothing if the key is not in the map.
  1566.      *
  1567.      * @param key the key that needs to be removed
  1568.      * @return the previous value associated with {@code key}, or {@code null} if there was no mapping for {@code key}
  1569.      * @throws NullPointerException if the specified key is null
  1570.      */
  1571.     @Override
  1572.     public V remove(final Object key) {
  1573.         final int hash = hashOf(key);
  1574.         return segmentFor(hash).remove(key, hash, null, false);
  1575.     }

  1576.     /**
  1577.      * {@inheritDoc}
  1578.      *
  1579.      * @throws NullPointerException if the specified key is null
  1580.      */
  1581.     @Override
  1582.     public boolean remove(final Object key, final Object value) {
  1583.         final int hash = hashOf(key);
  1584.         if (value == null) {
  1585.             return false;
  1586.         }
  1587.         return segmentFor(hash).remove(key, hash, value, false) != null;
  1588.     }

  1589.     /**
  1590.      * {@inheritDoc}
  1591.      *
  1592.      * @return the previous value associated with the specified key, or {@code null} if there was no mapping for the key
  1593.      * @throws NullPointerException if the specified key or value is null
  1594.      */
  1595.     @Override
  1596.     public V replace(final K key, final V value) {
  1597.         Objects.requireNonNull(value, "value");
  1598.         final int hash = hashOf(key);
  1599.         return segmentFor(hash).replace(key, hash, value);
  1600.     }

  1601.     /**
  1602.      * {@inheritDoc}
  1603.      *
  1604.      * @throws NullPointerException if any of the arguments are null
  1605.      */
  1606.     @Override
  1607.     public boolean replace(final K key, final V oldValue, final V newValue) {
  1608.         Objects.requireNonNull(oldValue, "oldValue");
  1609.         Objects.requireNonNull(newValue, "newValue");
  1610.         final int hash = hashOf(key);
  1611.         return segmentFor(hash).replace(key, hash, oldValue, newValue);
  1612.     }

  1613.     /**
  1614.      * Returns the segment that should be used for key with given hash
  1615.      *
  1616.      * @param hash the hash code for the key
  1617.      * @return the segment
  1618.      */
  1619.     private Segment<K, V> segmentFor(final int hash) {
  1620.         return segments[hash >>> segmentShift & segmentMask];
  1621.     }

  1622.     /**
  1623.      * Returns the number of key-value mappings in this map. If the map contains more than {@code Integer.MAX_VALUE} elements, returns
  1624.      * {@code Integer.MAX_VALUE}.
  1625.      *
  1626.      * @return the number of key-value mappings in this map
  1627.      */
  1628.     @Override
  1629.     public int size() {
  1630.         final Segment<K, V>[] segments = this.segments;
  1631.         long sum = 0;
  1632.         long check = 0;
  1633.         final int[] mc = new int[segments.length];
  1634.         // Try a few times to get accurate count. On failure due to
  1635.         // continuous async changes in table, resort to locking.
  1636.         for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
  1637.             check = 0;
  1638.             sum = 0;
  1639.             int mcsum = 0;
  1640.             for (int i = 0; i < segments.length; ++i) {
  1641.                 sum += segments[i].count;
  1642.                 mcsum += mc[i] = segments[i].modCount;
  1643.             }
  1644.             if (mcsum != 0) {
  1645.                 for (int i = 0; i < segments.length; ++i) {
  1646.                     check += segments[i].count;
  1647.                     if (mc[i] != segments[i].modCount) {
  1648.                         // force retry
  1649.                         check = -1;
  1650.                         break;
  1651.                     }
  1652.                 }
  1653.             }
  1654.             if (check == sum) {
  1655.                 break;
  1656.             }
  1657.         }
  1658.         if (check != sum) {
  1659.             // Resort to locking all segments
  1660.             sum = 0;
  1661.             for (final Segment<K, V> segment : segments) {
  1662.                 segment.lock();
  1663.             }
  1664.             for (final Segment<K, V> segment : segments) {
  1665.                 sum += segment.count;
  1666.             }
  1667.             for (final Segment<K, V> segment : segments) {
  1668.                 segment.unlock();
  1669.             }
  1670.         }
  1671.         return sum > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) sum;
  1672.     }

  1673.     /**
  1674.      * Returns a {@link Collection} view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the
  1675.      * collection, and vice-versa. The collection supports element removal, which removes the corresponding mapping from this map, via the
  1676.      * {@code Iterator.remove}, {@code Collection.remove}, {@code removeAll}, {@code retainAll}, and {@code clear} operations. It does not support the
  1677.      * {@code add} or {@code addAll} operations.
  1678.      * <p>
  1679.      * The view's {@code iterator} is a "weakly consistent" iterator that will never throw {@link ConcurrentModificationException}, and guarantees to traverse
  1680.      * elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.
  1681.      * </p>
  1682.      */
  1683.     @Override
  1684.     public Collection<V> values() {
  1685.         final Collection<V> vs = values;
  1686.         return vs != null ? vs : (values = new Values());
  1687.     }

  1688. }