Class WeakValueHashMap<K,V>
- Type Parameters:
K
- the class of key elements.V
- the class of value elements.
- All Implemented Interfaces:
Map<K,
V>
WeakValueHashMap
will automatically be removed when its value is no longer in ordinary use. This class is
similar to the standard WeakHashMap
class, except that weak references
apply to values rather than keys.
Note that this class is not a cache, because the entries are discarded
as soon as the garbage collector determines that they are no longer in use. If caching
service are wanted, or if concurrency are wanted, consider using Cache
instead.
This class is convenient for avoiding the creation of duplicated elements, as in the example below:
In the above example, the calculation of a new value needs to be fast because it is performed inside a synchronized statement blocking all other access to the map. This is okay if that particularWeakValueHashMap
instance
is not expected to be used in a highly concurrent environment.
WeakValueHashMap
works with array keys as one would expect. For example, arrays of int[]
are
compared using the Arrays.equals(int[], int[])
method.
Thread safety
The sameWeakValueHashMap
instance can be safely used by many threads without synchronization on the part
of the caller. But if a sequence of two or more method calls need to appear atomic from other threads perspective,
then the caller can synchronize on this
.- Since:
- 0.3
- Version:
- 1.2
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate final class
An entry in theWeakValueHashMap
.private final class
The set of entries.private static final class
Wildcard forintern(Object, Object, Object)
condition meaning whether a key shall be associated to a value or not.Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K extends Object,
V extends Object>, AbstractMap.SimpleImmutableEntry<K extends Object, V extends Object> -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final byte
Whether keys shall be compared by reference-equality (IDENTITY
), by shallow object-equality (EQUALS
) or by deep object-equality (DEEP_EQUALS
).private int
Number of non-null elements intable
.private static final byte
Comparison mode for key objects.The set of entries, created only when first needed.private static final byte
Comparison mode for key objects.private static final byte
Comparison mode for key objects.The type of the keys in this map.private long
The last time whentable
was not in need for rehash.private WeakValueHashMap<K,
V>.Entry[] Table of weak references. -
Constructor Summary
ConstructorsConstructorDescriptionWeakValueHashMap
(Class<K> keyType) Creates a newWeakValueHashMap
.WeakValueHashMap
(Class<K> keyType, boolean identity) Creates a newWeakValueHashMap
, optionally using reference-equality in place of object-equality. -
Method Summary
Modifier and TypeMethodDescriptionvoid
clear()
Removes all of the elements from this map.boolean
containsKey
(Object key) Returnstrue
if this map contains a mapping for the specified key.boolean
containsValue
(Object value) Returnstrue
if this map maps one or more keys to this value.entrySet()
Returns a set view of the mappings contained in this map.Returns the value to which this map maps the specified key.private V
Implementation ofput(Object, Object)
,putIfAbsent(Object, Object)
,remove(Object)
,replace(Object, Object)
andreplace(Object, Object, Object)
operations.(package private) final boolean
isValid()
Checks if thisWeakValueHashMap
is valid.(package private) final boolean
Returnstrue
if the two given keys are equal.(package private) final int
keyHashCode
(Object key) Returns the hash code value for the given key.Associates the specified value with the specified key in this map.putIfAbsent
(K key, V value) Associates the specified value with the specified key in this map if no value were previously associated.Removes the mapping for this key from this map if present.boolean
Removes the entry for the specified key only if it is currently mapped to the specified value.private void
removeEntry
(WeakValueHashMap<K, V>.Entry toRemove) Invoked byWeakValueHashMap<K,
when an element has been collected by the garbage collector.V>.Entry Replaces the entry for the specified key only if it is currently mapped to some value.boolean
Replaces the entry for the specified key only if currently mapped to the specified value.private boolean
replaceOrRemove
(Object key, Object oldValue, V newValue) Implementation ofreplace(Object, Object, Object)
andremove(Object, Object)
.int
size()
Returns the number of key-value mappings in this map.Methods inherited from class java.util.AbstractMap
clone, equals, hashCode, isEmpty, keySet, putAll, toString, values
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.util.Map
compute, computeIfAbsent, computeIfPresent, forEach, getOrDefault, merge, replaceAll
-
Field Details
-
IDENTITY
private static final byte IDENTITYComparison mode for key objects. The standard mode isEQUALS
, which means that keys are compared using theirObject.equals(Object)
method. ButWeakValueHashMap
will automatically selectDEEP_EQUALS
if there is a chance that some keys are arrays. In the latter case, comparisons will be done by the more costlyObjects.deepEquals(Object, Object)
method instead.The
IDENTITY
mode is rarely used, and is selected only if the user explicitly asks for this mode at construction time. This mode is provided because reference-equality semantic is sometimes required, and hard to simulate if not supported natively by the hash map. SeeIdentityHashMap
javadoc for some examples of cases where reference-equality semantic is useful. -
EQUALS
private static final byte EQUALSComparison mode for key objects. The standard mode isEQUALS
, which means that keys are compared using theirObject.equals(Object)
method. ButWeakValueHashMap
will automatically selectDEEP_EQUALS
if there is a chance that some keys are arrays. In the latter case, comparisons will be done by the more costlyObjects.deepEquals(Object, Object)
method instead.The
IDENTITY
mode is rarely used, and is selected only if the user explicitly asks for this mode at construction time. This mode is provided because reference-equality semantic is sometimes required, and hard to simulate if not supported natively by the hash map. SeeIdentityHashMap
javadoc for some examples of cases where reference-equality semantic is useful. -
DEEP_EQUALS
private static final byte DEEP_EQUALSComparison mode for key objects. The standard mode isEQUALS
, which means that keys are compared using theirObject.equals(Object)
method. ButWeakValueHashMap
will automatically selectDEEP_EQUALS
if there is a chance that some keys are arrays. In the latter case, comparisons will be done by the more costlyObjects.deepEquals(Object, Object)
method instead.The
IDENTITY
mode is rarely used, and is selected only if the user explicitly asks for this mode at construction time. This mode is provided because reference-equality semantic is sometimes required, and hard to simulate if not supported natively by the hash map. SeeIdentityHashMap
javadoc for some examples of cases where reference-equality semantic is useful. -
table
Table of weak references. -
count
private int countNumber of non-null elements intable
. This is used for determining whenWeakEntry.rehash(WeakEntry[], int, String)
needs to be invoked. -
keyType
The type of the keys in this map. -
comparisonMode
private final byte comparisonModeWhether keys shall be compared by reference-equality (IDENTITY
), by shallow object-equality (EQUALS
) or by deep object-equality (DEEP_EQUALS
). TheDEEP_EQUALS
mode is selected only if the keys in this map may be arrays. If the keys cannot be arrays, then we select theEQUALS
mode for avoiding calls to the costlyObjects.deepEquals(Object, Object)
method.- See Also:
-
entrySet
The set of entries, created only when first needed. -
lastTimeNormalCapacity
private transient long lastTimeNormalCapacity
-
-
Constructor Details
-
WeakValueHashMap
Creates a newWeakValueHashMap
.- Parameters:
keyType
- the type of keys in the map.
-
WeakValueHashMap
Creates a newWeakValueHashMap
, optionally using reference-equality in place of object-equality. Ifidentity
istrue
, then two keysk1
andk2
are considered equal if and only if(k1 == k2)
instead of ifk1.equals(k2)
.Reference-equality semantic is rarely used. See the
IdentityHashMap
class javadoc for a discussion about drawbacks and use cases when reference-equality semantic is useful.- Parameters:
keyType
- the type of keys in the map.identity
-true
if the map shall use reference-equality in place of object-equality when comparing keys, orfalse
for the standard behavior.- Since:
- 0.4
-
-
Method Details
-
removeEntry
Invoked byWeakValueHashMap<K,
when an element has been collected by the garbage collector. This method removes the weak reference from theV>.Entry table
.- Parameters:
toRemove
- the entry to remove from this map.
-
isValid
Checks if thisWeakValueHashMap
is valid. This method counts the number of elements and compares it tocount
. This method is invoked in assertions only.- Returns:
- whether
count
matches the expected value.
-
size
public int size()Returns the number of key-value mappings in this map. -
keyHashCode
Returns the hash code value for the given key.- Parameters:
key
- the key (cannot be null).
-
keyEquals
Returnstrue
if the two given keys are equal.- Parameters:
k1
- the first key (cannot be null).
-
containsKey
Returnstrue
if this map contains a mapping for the specified key. Null keys are considered never present.- Specified by:
containsKey
in interfaceMap<K,
V> - Overrides:
containsKey
in classAbstractMap<K,
V> - Parameters:
key
- key whose presence in this map is to be tested.- Returns:
true
if this map contains a mapping for the specified key.
-
containsValue
Returnstrue
if this map maps one or more keys to this value. Null values are considered never present.- Specified by:
containsValue
in interfaceMap<K,
V> - Overrides:
containsValue
in classAbstractMap<K,
V> - Parameters:
value
- value whose presence in this map is to be tested.- Returns:
true
if this map maps one or more keys to this value.
-
get
Returns the value to which this map maps the specified key. Returnsnull
if the map contains no mapping for this key. Null keys are considered never present. -
intern
Implementation ofput(Object, Object)
,putIfAbsent(Object, Object)
,remove(Object)
,replace(Object, Object)
andreplace(Object, Object, Object)
operations.- Parameters:
key
- key with which the specified value is to be associated.value
- value to be associated with the specified key, ornull
for removing the entry.condition
- previous value that entry must have for doing the action, ornull
if no restriction.- Returns:
- the previous value associated with specified key, or
null
if there was no mapping for the key.
-
put
Associates the specified value with the specified key in this map. The value is associated using aWeakReference
.- Specified by:
put
in interfaceMap<K,
V> - Overrides:
put
in classAbstractMap<K,
V> - Parameters:
key
- key with which the specified value is to be associated.value
- value to be associated with the specified key.- Returns:
- the previous value associated with specified key, or
null
if there was no mapping for the key. - Throws:
NullArgumentException
- if the key or the value isnull
.
-
putIfAbsent
Associates the specified value with the specified key in this map if no value were previously associated. If another value is already associated to the given key, then the map is left unchanged and the current value is returned. Otherwise the specified value is associated to the key using aWeakReference
andnull
is returned.- Parameters:
key
- key with which the specified value is to be associated.value
- value to be associated with the specified key.- Returns:
- the current value associated with specified key, or
null
if there was no mapping for the key. - Throws:
NullArgumentException
- if the key or the value isnull
.- Since:
- 0.7
-
replace
Replaces the entry for the specified key only if it is currently mapped to some value.- Parameters:
key
- key with which the specified value is to be associated.value
- value to be associated with the specified key.- Returns:
- the previous value associated with specified key, or
null
if there was no mapping for the key. - Throws:
NullArgumentException
- if the value isnull
.- Since:
- 1.2
-
replace
Replaces the entry for the specified key only if currently mapped to the specified value.- Parameters:
key
- key with which the specified value is to be associated.oldValue
- value expected to be associated with the specified key.newValue
- value to be associated with the specified key.- Returns:
true
if the value was replaced.- Throws:
NullArgumentException
- if the new value isnull
.- Since:
- 1.2
-
remove
Removes the mapping for this key from this map if present. -
remove
Removes the entry for the specified key only if it is currently mapped to the specified value.- Parameters:
key
- key whose mapping is to be removed from the map.value
- value expected to be associated with the specified key.- Returns:
true
if the value was removed.- Since:
- 1.2
-
replaceOrRemove
Implementation ofreplace(Object, Object, Object)
andremove(Object, Object)
. The replace action has a non-nullnewValue
and the remove action has a null new value. -
clear
public void clear()Removes all of the elements from this map. -
entrySet
Returns a set view of the mappings contained in this map. Each element in this set is aMap.Entry
.
-