Overview | Package | Class | Use | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

## com.google.common.collect
Class MapMaker

    java.lang.Object
      com.google.common.collect.GenericMapMaker<Object,Object>
          com.google.common.collect.MapMaker

    @GwtCompatible(emulated=true)
    public final class MapMaker

extends GenericMapMaker<Object,Object>

A builder of `ConcurrentMap` instances having any combination of the following features:

- keys or values automatically wrapped in weak or soft references
- least-recently-used eviction when a maximum size is exceeded
- time-based expiration of entries, measured since last access or last write
- notification of evicted (or otherwise removed) entries
- on-demand computation of values for keys not already present

Usage example:

       ConcurrentMap<Key, Graph> graphs = new MapMaker()
           .concurrencyLevel(4)
           .weakKeys()
           .maximumSize(10000)
           .expireAfterWrite(10, TimeUnit.MINUTES)
           .makeComputingMap(
               new Function<Key, Graph>() {
                 public Graph apply(Key key) {
                   return createExpensiveGraph(key);
                 }
               });

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()` or `softKeys()` was specified, the map uses identity (`==`) comparisons instead for keys. Likewise, if `weakValues()` or `softValues()` 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 soft or weak references were requested, it is possible for a key or value present in the the map to be reclaimed by the garbage collector. If this happens, the entry automatically disappears from the map. 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(V)`, which simply calls `Map.put(K, V)` 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 soft or 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 `WeakHashMap`, but note that it compares keys using object identity whereas `WeakHashMap` uses `Object.equals(java.lang.Object)`.

Since:
  2.0 (imported from Google Collections Library)
Author:
  Bob Lee, Charles Fry, Kevin Bourrillion

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

Method Summary
`MapMaker` | `concurrencyLevel(int concurrencyLevel)` Guides the allowed concurrency among update operations.
`
`<K,V> GenericMapMaker<K,V>`
` | `evictionListener(MapEvictionListener<K,V> listener)` Deprecated. Caching functionality in `MapMaker` is being moved to `CacheBuilder`. Functionality similar to `evictionListener(com.google.common.collect.MapEvictionListener)` is provided by `CacheBuilder.removalListener(com.google.common.cache.RemovalListener)` which also provides additional information about the entry being evicted; note that `evictionListener` only notifies on removals due to eviction, while `removalListener` also notifies on explicit removal (providing the `RemovalCause` to indicate the specific cause of removal. This method is scheduled for deletion in Guava release 11.
`MapMaker` | `expiration(long duration, TimeUnit unit)` Deprecated. Caching functionality in `MapMaker` is being moved to `CacheBuilder`. Functionality equivalent to `expiration(long, java.util.concurrent.TimeUnit)` is provided by `CacheBuilder.expireAfterWrite(long, java.util.concurrent.TimeUnit)`. This method is scheduled for deletion in July 2012.
`MapMaker` | `expireAfterAccess(long duration, TimeUnit unit)` Deprecated.
`MapMaker` | `expireAfterWrite(long duration, TimeUnit unit)` Deprecated.
`MapMaker` | `initialCapacity(int initialCapacity)` Sets the minimum total size for the internal hash tables.
`
`<K,V> ConcurrentMap<K,V>`
` | `makeComputingMap(Function<? super K,? extends V> computingFunction)` Deprecated.
`
`<K,V> ConcurrentMap<K,V>`
` | `makeMap()` Builds a thread-safe map, without on-demand computation of values.
`MapMaker` | `maximumSize(int size)` Deprecated.
`MapMaker` | `softKeys()` Deprecated. use `softValues()` to create a memory-sensitive map, or `weakKeys()` to create a map that doesn't hold strong references to the keys. This method is scheduled for deletion in January 2013.
`MapMaker` | `softValues()` Specifies that each value (not key) stored in the map should be wrapped in a `SoftReference` (by default, strong references are used).
`String` | `toString()` Returns a string representation for this MapMaker instance.
`MapMaker` | `weakKeys()` Specifies that each key (not value) stored in the map should be wrapped in a `WeakReference` (by default, strong references are used).
`MapMaker` | `weakValues()` Specifies that each value (not key) stored in the map should be wrapped in a `WeakReference` (by default, strong references are used).

Methods inherited from class java.lang.Object
`clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

Constructor Detail

### MapMaker

    public MapMaker()

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

Method Detail

### initialCapacity

    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.

  Specified by:
    `initialCapacity` in class `GenericMapMaker<Object,Object>`
  Throws:
    `IllegalArgumentException` - if `initialCapacity` is negative
    `IllegalStateException` - if an initial capacity was already set

### maximumSize

    @Beta
    @Deprecated
    public MapMaker maximumSize(int size)

  Deprecated.

  Specifies the maximum number of entries the map may contain. Note that the map may evict an entry before this limit is exceeded. As the map size grows close to the maximum, the map evicts entries that are less likely to be used again. For example, the map may evict an entry because it hasn't been used recently or very often.

  When `size` is zero, elements can be successfully added to the map, but are evicted immediately. This has the same effect as invoking `expireAfterWrite``(0, unit)` or `expireAfterAccess``(0, unit)`. It can be useful in testing, or to disable caching temporarily without a code change.

  Caching functionality in `MapMaker` is being moved to `CacheBuilder`. This method is scheduled for deletion from Guava in Guava release 11.0.

  Specified by:
    `maximumSize` in class `GenericMapMaker<Object,Object>`
  Parameters:
    `size` - the maximum size of the map
  Throws:
    `IllegalArgumentException` - if `size` is negative
    `IllegalStateException` - if a maximum size was already set
  Since:
    8.0

### concurrencyLevel

    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.

  Specified by:
    `concurrencyLevel` in class `GenericMapMaker<Object,Object>`
  Throws:
    `IllegalArgumentException` - if `concurrencyLevel` is nonpositive
    `IllegalStateException` - if a concurrency level was already set

### weakKeys

    @GwtIncompatible(value="java.lang.ref.WeakReference")
    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.

  Specified by:
    `weakKeys` in class `GenericMapMaker<Object,Object>`
  Throws:
    `IllegalStateException` - if the key strength was already set
  See Also:
    `WeakReference`

### softKeys

    @Deprecated
    @GwtIncompatible(value="java.lang.ref.SoftReference")
    public MapMaker softKeys()

  Deprecated. use `softValues()` to create a memory-sensitive map, or `weakKeys()` to create a map that doesn't hold strong references to the keys. This method is scheduled for deletion in January 2013.

  Specifies that each key (not value) stored in the map should be wrapped in a `SoftReference` (by default, strong references are used). Softly-referenced objects will be garbage-collected in a globally least-recently-used manner, in response to memory demand.

  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.

  Specified by:
    `softKeys` in class `GenericMapMaker<Object,Object>`
  Throws:
    `IllegalStateException` - if the key strength was already set
  See Also:
    `SoftReference`

### weakValues

    @GwtIncompatible(value="java.lang.ref.WeakReference")
    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; consider `softValues()` instead.

  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.

  Specified by:
    `weakValues` in class `GenericMapMaker<Object,Object>`
  Throws:
    `IllegalStateException` - if the value strength was already set
  See Also:
    `WeakReference`

### softValues

    @GwtIncompatible(value="java.lang.ref.SoftReference")
    public MapMaker softValues()

  Specifies that each value (not key) stored in the map should be wrapped in a `SoftReference` (by default, strong references are used). Softly-referenced objects will be garbage-collected in a globally least-recently-used manner, in response to memory demand.

  Warning: in most circumstances it is better to set a per-cache maximum size instead of using soft references. You should only use this method if you are well familiar with the practical consequences of soft references.

  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.

  Specified by:
    `softValues` in class `GenericMapMaker<Object,Object>`
  Throws:
    `IllegalStateException` - if the value strength was already set
  See Also:
    `SoftReference`

### expiration

    @Deprecated
    public MapMaker expiration(long duration,
                                          TimeUnit unit)

  Deprecated. Caching functionality in `MapMaker` is being moved to `CacheBuilder`. Functionality equivalent to `expiration(long, java.util.concurrent.TimeUnit)` is provided by `CacheBuilder.expireAfterWrite(long, java.util.concurrent.TimeUnit)`. This method is scheduled for deletion in July 2012.

  Old name of `expireAfterWrite(long, java.util.concurrent.TimeUnit)`.

  Specified by:
    `expiration` in class `GenericMapMaker<Object,Object>`

### expireAfterWrite

    @Deprecated
    public MapMaker expireAfterWrite(long duration,
                                                TimeUnit unit)

  Deprecated.

  Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

  When `duration` is zero, elements can be successfully added to the map, but are evicted immediately. This has a very similar effect to invoking `maximumSize``(0)`. It can be useful in testing, or to disable caching temporarily without a code change.

  Expired entries may be counted by `Map.size()`, but will never be visible to read or write operations. Expired entries are currently cleaned up during write operations, or during occasional read operations in the absense of writes; though this behavior may change in the future.

  Caching functionality in `MapMaker` is being moved to `CacheBuilder`. This method is scheduled for deletion from Guava in Guava release 11.0.

  Specified by:
    `expireAfterWrite` in class `GenericMapMaker<Object,Object>`
  Parameters:
    `duration` - the length of time after an entry is created that it should be automatically removed
    `unit` - the unit that `duration` is expressed in
  Throws:
    `IllegalArgumentException` - if `duration` is negative
    `IllegalStateException` - if the time to live or time to idle was already set
  Since:
    8.0

### expireAfterAccess

    @GwtIncompatible(value="To be supported")
    @Deprecated
    public MapMaker expireAfterAccess(long duration,
                                                                      TimeUnit unit)

  Deprecated.

  Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's last read or write access.

  When `duration` is zero, elements can be successfully added to the map, but are evicted immediately. This has a very similar effect to invoking `maximumSize``(0)`. It can be useful in testing, or to disable caching temporarily without a code change.

  Expired entries may be counted by `Map.size()`, but will never be visible to read or write operations. Expired entries are currently cleaned up during write operations, or during occasional read operations in the absense of writes; though this behavior may change in the future.

  Caching functionality in `MapMaker` is being moved to `CacheBuilder`. This method is scheduled for deletion from Guava in Guava release 11.0.

  Specified by:
    `expireAfterAccess` in class `GenericMapMaker<Object,Object>`
  Parameters:
    `duration` - the length of time after an entry is last accessed that it should be automatically removed
    `unit` - the unit that `duration` is expressed in
  Throws:
    `IllegalArgumentException` - if `duration` is negative
    `IllegalStateException` - if the time to idle or time to live was already set
  Since:
    8.0

### evictionListener

    @Beta
    @Deprecated
    @GwtIncompatible(value="To be supported")
    public <K,V> GenericMapMaker<K,V> evictionListener(MapEvictionListener<K,V> listener)

  Deprecated. Caching functionality in `MapMaker` is being moved to `CacheBuilder`. Functionality similar to `evictionListener(com.google.common.collect.MapEvictionListener)` is provided by `CacheBuilder.removalListener(com.google.common.cache.RemovalListener)` which also provides additional information about the entry being evicted; note that `evictionListener` only notifies on removals due to eviction, while `removalListener` also notifies on explicit removal (providing the `RemovalCause` to indicate the specific cause of removal. This method is scheduled for deletion in Guava release 11.

  Specifies a listener instance, which all maps built using this `MapMaker` will notify each time an entry is evicted.

  A map built by this map maker will invoke the supplied listener after it evicts an entry, whether it does so due to timed expiration, exceeding the maximum size, or discovering that the key or value has been reclaimed by the garbage collector. It will invoke the listener during invocations of any of that map's public methods (even read-only methods). The listener will not be invoked on manual removal.

  Important note: Instead of returning this as a `MapMaker` instance, this method returns `GenericMapMaker<K, V>`. From this point on, either the original reference or the returned reference may be used to complete configuration and build the map, but only the "generic" one is type-safe. That is, it will properly prevent you from building maps whose key or value types are incompatible with the types accepted by the listener already provided; the `MapMaker` type cannot do this. For best results, simply use the standard method-chaining idiom, as illustrated in the documentation at top, configuring a `MapMaker` and building your `Map` all in a single statement.

  Warning: if you ignore the above advice, and use this `MapMaker` to build maps whose key or value types are incompatible with the listener, you will likely experience a `ClassCastException` at an undefined point in the future.

  Throws:
    `IllegalStateException` - if an eviction listener was already set
  Since:
    7.0

### makeMap

    public <K,V> ConcurrentMap<K,V> makeMap()

  Builds a thread-safe map, without on-demand computation of values. 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.

  Specified by:
    `makeMap` in class `GenericMapMaker<Object,Object>`
  Returns:
    a serializable concurrent map having the requested features

### makeComputingMap

    @Deprecated
    public <K,V> ConcurrentMap<K,V> makeComputingMap(Function<? super K,? extends V> computingFunction)

  Deprecated.

  Builds a map that supports atomic, on-demand computation of values. `Map.get(java.lang.Object)` either returns an already-computed value for the given key, atomically computes it using the supplied function, or, if another thread is currently computing the value for this key, simply waits for that thread to finish and returns its computed value. Note that the function may be executed concurrently by multiple threads, but only for distinct keys.

  New code should use `CacheBuilder`, which supports statistics collection, introduces the `CacheLoader` interface for loading entries into the cache (allowing checked exceptions to be thrown in the process), and more cleanly separates computation from the cache's `Map` view.

  If an entry's value has not finished computing yet, query methods besides `get` return immediately as if an entry doesn't exist. In other words, an entry isn't externally visible until the value's computation completes.

  `Map.get(java.lang.Object)` on the returned map will never return `null`. It may throw:

  - `NullPointerException` if the key is null or the computing function returns a null result
  - `ComputationException` if an exception was thrown by the computing function. If that exception is already of type `ComputationException` it is propagated directly; otherwise it is wrapped.

  Note: Callers of `get` must ensure that the key argument is of type `K`. The `get` method accepts `Object`, so the key type is not checked at compile time. Passing an object of a type other than `K` can result in that object being unsafely passed to the computing function as type `K`, and unsafely stored in the map.

  If `Map.put(K, V)` is called before a computation completes, other threads waiting on the computation will wake up and return the stored value.

  This method does not alter the state of this `MapMaker` instance, so it can be invoked again to create multiple independent maps.

  Insertion, removal, update, and access operations on the returned map safely execute concurrently by multiple threads. Iterators on the returned map are weakly consistent, returning elements reflecting the state of the map at some point at or since the creation of the iterator. They do not throw `ConcurrentModificationException`, and may proceed concurrently with other operations.

  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.

  Caching functionality in `MapMaker` is being moved to `CacheBuilder`, with `makeComputingMap(com.google.common.base.Function)` being replaced by `CacheBuilder.build(com.google.common.cache.CacheLoader)`. CacheBuilder does not yet support manual insertion, so writeable maps should continue using makeComputingMap until release 11.0. This method is scheduled for deletion in February 2013.

  Specified by:
    `makeComputingMap` in class `GenericMapMaker<Object,Object>`
  Parameters:
    `computingFunction` - the function used to compute new values
  Returns:
    a serializable concurrent map having the requested features

### toString

    public String toString()

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

  Overrides:
    `toString` in class `Object`

Overview | Package | Class | Use | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

Copyright © 2010-2011. All Rights Reserved.