Top Description Inners Fields Constructors Methods
com.google.common.collect

public final Class MapMaker

extends Object
Class Inheritance
Annotations
@J2ktIncompatible
@GwtCompatible
emulated:true
@ElementTypesAreNonnullByDefault
Static Imports
com.google.common.base.Preconditions.checkArgument, .Preconditions.checkNotNull, .Preconditions.checkState

A builder of ConcurrentMap instances that can have keys or values automatically wrapped in weak references.

Usage example:

ConcurrentMap<Request, Stopwatch> timers = new MapMaker()
    .concurrencyLevel(4)
    .weakKeys()
    .makeMap();

These features are all optional; new MapMaker().makeMap() returns a valid concurrent map that behaves similarly to a ConcurrentHashMap.

The returned map is implemented as a hash table with similar performance characteristics to ConcurrentHashMap. It supports all optional operations of the ConcurrentMap interface. It does not permit null keys or values.

Note

by default, the returned map uses equality comparisons (the equals method) to determine equality for keys or values. However, if weakKeys was specified, the map uses identity (==) comparisons instead for keys. Likewise, if weakValues was specified, the map uses identity comparisons for values.

The view collections of the returned map have weakly consistent iterators. This means that they are safe for concurrent use, but if other threads modify the map after the iterator is created, it is undefined which of these changes, if any, are reflected in that iterator. These iterators never throw ConcurrentModificationException.

If weakKeys or weakValues are requested, it is possible for a key or value present in the map to be reclaimed by the garbage collector. Entries with reclaimed keys or values may be removed from the map on each map modification or on occasional map accesses; such entries may be counted by Map#size, but will never be visible to read or write operations. A partially-reclaimed entry is never exposed to the user. Any Map.Entry instance retrieved from the map's entry set is a snapshot of that entry's state at the time of retrieval; such entries do, however, support Map.Entry#setValue, which simply calls Map#put on the entry's key.

The maps produced by MapMaker are serializable, and the deserialized maps retain all the configuration properties of the original map. During deserialization, if the original map had used weak references, the entries are reconstructed as they were, but it's not unlikely they'll be quickly garbage-collected before they are ever accessed.

new MapMaker().weakKeys().makeMap() is a recommended replacement for java.util.WeakHashMap, but note that it compares keys using object identity whereas WeakHashMap uses Object#equals.

Authors
Bob Lee, Charles Fry, Kevin Bourrillion
Since
2.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static enum
MapMaker.Dummy

A dummy singleton value type used by Interners.

Field Summary

Modifier and TypeField and Description
pack-priv int
private static final int
private static final int
pack-priv int
pack-priv Equivalence<Object>
pack-priv MapMakerInternalMap.Strength
pack-priv static final int
pack-priv boolean
pack-priv MapMakerInternalMap.Strength

Constructor Summary

AccessConstructor and Description
public
MapMaker()

Constructs a new MapMaker instance with default settings, including strong keys, strong values, and no automatic eviction of any kind.

Method Summary

Modifier and TypeMethod and Description
public MapMaker
concurrencyLevel(int concurrencyLevel)

Guides the allowed concurrency among update operations.

pack-priv int
pack-priv int
pack-priv Equivalence<Object>
pack-priv MapMakerInternalMap.Strength
pack-priv MapMakerInternalMap.Strength
public MapMaker
initialCapacity(int initialCapacity)

Sets the minimum total size for the internal hash tables.

pack-priv MapMaker
keyEquivalence(Equivalence<Object> equivalence)

Sets a custom Equivalence strategy for comparing keys.

public <K, V> ConcurrentMap<K, V>

Returns:

a serializable concurrent map having the requested features
makeMap
()

Builds a thread-safe map.

pack-priv MapMaker
pack-priv MapMaker
public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation for this MapMaker instance.
public MapMaker
weakKeys()

Specifies that each key (not value) stored in the map should be wrapped in a WeakReference (by default, strong references are used).

public MapMaker
weakValues()

Specifies that each value (not key) stored in the map should be wrapped in a WeakReference (by default, strong references are used).

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

Field Detail

concurrencyLevelback to summary
pack-priv int concurrencyLevel
DEFAULT_CONCURRENCY_LEVELback to summary
private static final int DEFAULT_CONCURRENCY_LEVEL
DEFAULT_INITIAL_CAPACITYback to summary
private static final int DEFAULT_INITIAL_CAPACITY
initialCapacityback to summary
pack-priv int initialCapacity
keyEquivalenceback to summary
pack-priv Equivalence<Object> keyEquivalence
Annotations
@CheckForNull
keyStrengthback to summary
pack-priv MapMakerInternalMap.Strength keyStrength
Annotations
@CheckForNull
UNSET_INTback to summary
pack-priv static final int UNSET_INT
useCustomMapback to summary
pack-priv boolean useCustomMap
valueStrengthback to summary
pack-priv MapMakerInternalMap.Strength valueStrength
Annotations
@CheckForNull

Constructor Detail

MapMakerback to summary
public MapMaker()

Constructs a new MapMaker instance with default settings, including strong keys, strong values, and no automatic eviction of any kind.

Method Detail

concurrencyLevelback to summary
public MapMaker concurrencyLevel(int concurrencyLevel)

Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The table is internally partitioned to try to permit the indicated number of concurrent updates without contention. Because assignment of entries to these partitions is not necessarily uniform, the actual concurrency observed may vary. Ideally, you should choose a value to accommodate as many threads as will ever concurrently modify the table. Using a significantly higher value than you need can waste space and time, and a significantly lower value can lead to thread contention. But overestimates and underestimates within an order of magnitude do not usually have much noticeable impact. A value of one permits only one thread to modify the map at a time, but since read operations can proceed concurrently, this still yields higher concurrency than full synchronization. Defaults to 4.

Note

Prior to Guava release 9.0, the default was 16. It is possible the default will change again in the future. If you care about this value, you should always choose it explicitly.

Annotations
@CanIgnoreReturnValue
Exceptions
IllegalArgumentException:
if concurrencyLevel is nonpositive
IllegalStateException:
if a concurrency level was already set
getConcurrencyLevelback to summary
pack-priv int getConcurrencyLevel()
getInitialCapacityback to summary
pack-priv int getInitialCapacity()
getKeyEquivalenceback to summary
pack-priv Equivalence<Object> getKeyEquivalence()
getKeyStrengthback to summary
pack-priv MapMakerInternalMap.Strength getKeyStrength()
getValueStrengthback to summary
pack-priv MapMakerInternalMap.Strength getValueStrength()
initialCapacityback to summary
public MapMaker initialCapacity(int initialCapacity)

Sets the minimum total size for the internal hash tables. For example, if the initial capacity is 60, and the concurrency level is 8, then eight segments are created, each having a hash table of size eight. Providing a large enough estimate at construction time avoids the need for expensive resizing operations later, but setting this value unnecessarily high wastes memory.

Annotations
@CanIgnoreReturnValue
Exceptions
IllegalArgumentException:
if initialCapacity is negative
IllegalStateException:
if an initial capacity was already set
keyEquivalenceback to summary
pack-priv MapMaker keyEquivalence(Equivalence<Object> equivalence)

Sets a custom Equivalence strategy for comparing keys.

By default, the map uses Equivalence#identity to determine key equality when weakKeys is specified, and Equivalence#equals() otherwise. The only place this is used is in Interners.WeakInterner.

Annotations
@CanIgnoreReturnValue
@GwtIncompatible
makeMapback to summary
public <K, V> ConcurrentMap<K, V> makeMap()

Builds a thread-safe map. This method does not alter the state of this MapMaker instance, so it can be invoked again to create multiple independent maps.

The bulk operations putAll, equals, and clear are not guaranteed to be performed atomically on the returned map. Additionally, size and containsValue are implemented as bulk read operations, and thus may fail to observe concurrent writes.

Returns:ConcurrentMap<K, V>

a serializable concurrent map having the requested features

setKeyStrengthback to summary
pack-priv MapMaker setKeyStrength(MapMakerInternalMap.Strength strength)
setValueStrengthback to summary
pack-priv MapMaker setValueStrength(MapMakerInternalMap.Strength strength)
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Returns a string representation for this MapMaker instance. The exact form of the returned string is not specified.

Returns:String

Doc from java.lang.Object.toString.

a string representation of the object.

Annotations
@Override
weakKeysback to summary
public MapMaker weakKeys()

Specifies that each key (not value) stored in the map should be wrapped in a WeakReference (by default, strong references are used).

Warning

when this method is used, the resulting map will use identity (==) comparison to determine equality of keys, which is a technical violation of the Map specification, and may not be what you expect.

Annotations
@CanIgnoreReturnValue
@GwtIncompatible
Exceptions
IllegalStateException:
if the key strength was already set
See Also
WeakReference
weakValuesback to summary
public MapMaker weakValues()

Specifies that each value (not key) stored in the map should be wrapped in a WeakReference (by default, strong references are used).

Weak values will be garbage collected once they are weakly reachable. This makes them a poor candidate for caching.

Warning

when this method is used, the resulting map will use identity (==) comparison to determine equality of values. This technically violates the specifications of the methods containsValue, remove(Object, Object) and replace(K, V, V), and may not be what you expect.

Annotations
@CanIgnoreReturnValue
@GwtIncompatible
Exceptions
IllegalStateException:
if the value strength was already set
See Also
WeakReference
com.google.common.collect back to summary

pack-priv final Enum MapMaker.Dummy

extends Enum<MapMaker.Dummy>
Class Inheritance

A dummy singleton value type used by Interners.

MapMakerInternalMap can optimize for memory usage in this case; see MapMakerInternalMap#createWithDummyValues.

Field Summary

Modifier and TypeField and Description
public static final MapMaker.Dummy

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static MapMaker.Dummy
public static MapMaker.Dummy[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

VALUEback to summary
public static final MapMaker.Dummy VALUE

Constructor Detail

Dummyback to summary
private Dummy()

Method Detail

valueOfback to summary
public static MapMaker.Dummy valueOf(String name)
valuesback to summary
public static MapMaker.Dummy[] values()