001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.collect;
016
017import static com.google.common.base.Objects.firstNonNull;
018import static com.google.common.base.Preconditions.checkArgument;
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkState;
021import static com.google.common.collect.MapMakerInternalMap.Strength.SOFT;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.base.Ascii;
026import com.google.common.base.Equivalence;
027import com.google.common.base.Function;
028import com.google.common.base.Objects;
029import com.google.common.base.Throwables;
030import com.google.common.base.Ticker;
031import com.google.common.collect.MapMakerInternalMap.Strength;
032
033import java.io.Serializable;
034import java.lang.ref.SoftReference;
035import java.lang.ref.WeakReference;
036import java.util.AbstractMap;
037import java.util.Collections;
038import java.util.ConcurrentModificationException;
039import java.util.Map;
040import java.util.Set;
041import java.util.concurrent.ConcurrentHashMap;
042import java.util.concurrent.ConcurrentMap;
043import java.util.concurrent.ExecutionException;
044import java.util.concurrent.TimeUnit;
045
046import javax.annotation.Nullable;
047
048/**
049 * <p>A builder of {@link ConcurrentMap} instances having any combination of the following features:
050 *
051 * <ul>
052 * <li>keys or values automatically wrapped in {@linkplain WeakReference weak} or {@linkplain
053 *     SoftReference soft} references
054 * <li>notification of evicted (or otherwise removed) entries
055 * <li>on-demand computation of values for keys not already present
056 * </ul>
057 *
058 * <p>Usage example: <pre>   {@code
059 *
060 *   ConcurrentMap<Key, Graph> graphs = new MapMaker()
061 *       .concurrencyLevel(4)
062 *       .weakKeys()
063 *       .makeComputingMap(
064 *           new Function<Key, Graph>() {
065 *             public Graph apply(Key key) {
066 *               return createExpensiveGraph(key);
067 *             }
068 *           });}</pre>
069 *
070 * These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent map
071 * that behaves similarly to a {@link ConcurrentHashMap}.
072 *
073 * <p>The returned map is implemented as a hash table with similar performance characteristics to
074 * {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap}
075 * interface. It does not permit null keys or values.
076 *
077 * <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals
078 * equals} method) to determine equality for keys or values. However, if {@link #weakKeys} was
079 * specified, the map uses identity ({@code ==}) comparisons instead for keys. Likewise, if {@link
080 * #weakValues} or {@link #softValues} was specified, the map uses identity comparisons for values.
081 *
082 * <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means
083 * that they are safe for concurrent use, but if other threads modify the map after the iterator is
084 * created, it is undefined which of these changes, if any, are reflected in that iterator. These
085 * iterators never throw {@link ConcurrentModificationException}.
086 *
087 * <p>If soft or weak references were requested, it is possible for a key or value present in the
088 * the map to be reclaimed by the garbage collector. If this happens, the entry automatically
089 * disappears from the map. A partially-reclaimed entry is never exposed to the user. Any {@link
090 * java.util.Map.Entry} instance retrieved from the map's {@linkplain Map#entrySet entry set} is a
091 * snapshot of that entry's state at the time of retrieval; such entries do, however, support {@link
092 * java.util.Map.Entry#setValue}, which simply calls {@link Map#put} on the entry's key.
093 *
094 * <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all
095 * the configuration properties of the original map. During deserialization, if the original map had
096 * used soft or weak references, the entries are reconstructed as they were, but it's not unlikely
097 * they'll be quickly garbage-collected before they are ever accessed.
098 *
099 * <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link
100 * java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code
101 * WeakHashMap} uses {@link Object#equals}.
102 *
103 * @author Bob Lee
104 * @author Charles Fry
105 * @author Kevin Bourrillion
106 * @since 2.0 (imported from Google Collections Library)
107 */
108@GwtCompatible(emulated = true)
109public final class MapMaker extends GenericMapMaker<Object, Object> {
110  private static final int DEFAULT_INITIAL_CAPACITY = 16;
111  private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
112  private static final int DEFAULT_EXPIRATION_NANOS = 0;
113
114  static final int UNSET_INT = -1;
115
116  // TODO(kevinb): dispense with this after benchmarking
117  boolean useCustomMap;
118
119  int initialCapacity = UNSET_INT;
120  int concurrencyLevel = UNSET_INT;
121  int maximumSize = UNSET_INT;
122
123  Strength keyStrength;
124  Strength valueStrength;
125
126  long expireAfterWriteNanos = UNSET_INT;
127  long expireAfterAccessNanos = UNSET_INT;
128
129  RemovalCause nullRemovalCause;
130
131  Equivalence<Object> keyEquivalence;
132
133  Ticker ticker;
134
135  /**
136   * Constructs a new {@code MapMaker} instance with default settings, including strong keys, strong
137   * values, and no automatic eviction of any kind.
138   */
139  public MapMaker() {}
140
141  /**
142   * Sets a custom {@code Equivalence} strategy for comparing keys.
143   *
144   * <p>By default, the map uses {@link Equivalence#identity} to determine key equality when {@link
145   * #weakKeys} is specified, and {@link Equivalence#equals()} otherwise. The only place this is
146   * used is in {@link Interners.WeakInterner}.
147   */
148  @GwtIncompatible("To be supported")
149  @Override
150  MapMaker keyEquivalence(Equivalence<Object> equivalence) {
151    checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
152    keyEquivalence = checkNotNull(equivalence);
153    this.useCustomMap = true;
154    return this;
155  }
156
157  Equivalence<Object> getKeyEquivalence() {
158    return firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
159  }
160
161  /**
162   * Sets the minimum total size for the internal hash tables. For example, if the initial capacity
163   * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
164   * having a hash table of size eight. Providing a large enough estimate at construction time
165   * avoids the need for expensive resizing operations later, but setting this value unnecessarily
166   * high wastes memory.
167   *
168   * @throws IllegalArgumentException if {@code initialCapacity} is negative
169   * @throws IllegalStateException if an initial capacity was already set
170   */
171  @Override
172  public MapMaker initialCapacity(int initialCapacity) {
173    checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s",
174        this.initialCapacity);
175    checkArgument(initialCapacity >= 0);
176    this.initialCapacity = initialCapacity;
177    return this;
178  }
179
180  int getInitialCapacity() {
181    return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
182  }
183
184  /**
185   * Specifies the maximum number of entries the map may contain. Note that the map <b>may evict an
186   * entry before this limit is exceeded</b>. As the map size grows close to the maximum, the map
187   * evicts entries that are less likely to be used again. For example, the map may evict an entry
188   * because it hasn't been used recently or very often.
189   *
190   * <p>When {@code size} is zero, elements can be successfully added to the map, but are evicted
191   * immediately. This has the same effect as invoking {@link #expireAfterWrite
192   * expireAfterWrite}{@code (0, unit)} or {@link #expireAfterAccess expireAfterAccess}{@code (0,
193   * unit)}. It can be useful in testing, or to disable caching temporarily without a code change.
194   *
195   * <p>Caching functionality in {@code MapMaker} is being moved to
196   * {@link com.google.common.cache.CacheBuilder}.
197   *
198   * @param size the maximum size of the map
199   * @throws IllegalArgumentException if {@code size} is negative
200   * @throws IllegalStateException if a maximum size was already set
201   * @deprecated Caching functionality in {@code MapMaker} is being moved to
202   *     {@link com.google.common.cache.CacheBuilder}, with {@link #maximumSize} being
203   *     replaced by {@link com.google.common.cache.CacheBuilder#maximumSize}. Note that {@code
204   *     CacheBuilder} is simply an enhanced API for an implementation which was branched from
205   *     {@code MapMaker}.
206   */
207  @Deprecated
208  @Override
209  MapMaker maximumSize(int size) {
210    checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
211        this.maximumSize);
212    checkArgument(size >= 0, "maximum size must not be negative");
213    this.maximumSize = size;
214    this.useCustomMap = true;
215    if (maximumSize == 0) {
216      // SIZE trumps EXPIRED
217      this.nullRemovalCause = RemovalCause.SIZE;
218    }
219    return this;
220  }
221
222  /**
223   * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
224   * table is internally partitioned to try to permit the indicated number of concurrent updates
225   * without contention. Because assignment of entries to these partitions is not necessarily
226   * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
227   * accommodate as many threads as will ever concurrently modify the table. Using a significantly
228   * higher value than you need can waste space and time, and a significantly lower value can lead
229   * to thread contention. But overestimates and underestimates within an order of magnitude do not
230   * usually have much noticeable impact. A value of one permits only one thread to modify the map
231   * at a time, but since read operations can proceed concurrently, this still yields higher
232   * concurrency than full synchronization. Defaults to 4.
233   *
234   * <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will
235   * change again in the future. If you care about this value, you should always choose it
236   * explicitly.
237   *
238   * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
239   * @throws IllegalStateException if a concurrency level was already set
240   */
241  @Override
242  public MapMaker concurrencyLevel(int concurrencyLevel) {
243    checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s",
244        this.concurrencyLevel);
245    checkArgument(concurrencyLevel > 0);
246    this.concurrencyLevel = concurrencyLevel;
247    return this;
248  }
249
250  int getConcurrencyLevel() {
251    return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
252  }
253
254  /**
255   * Specifies that each key (not value) stored in the map should be wrapped in a {@link
256   * WeakReference} (by default, strong references are used).
257   *
258   * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
259   * comparison to determine equality of keys, which is a technical violation of the {@link Map}
260   * specification, and may not be what you expect.
261   *
262   * @throws IllegalStateException if the key strength was already set
263   * @see WeakReference
264   */
265  @GwtIncompatible("java.lang.ref.WeakReference")
266  @Override
267  public MapMaker weakKeys() {
268    return setKeyStrength(Strength.WEAK);
269  }
270
271  MapMaker setKeyStrength(Strength strength) {
272    checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
273    keyStrength = checkNotNull(strength);
274    checkArgument(keyStrength != SOFT, "Soft keys are not supported");
275    if (strength != Strength.STRONG) {
276      // STRONG could be used during deserialization.
277      useCustomMap = true;
278    }
279    return this;
280  }
281
282  Strength getKeyStrength() {
283    return firstNonNull(keyStrength, Strength.STRONG);
284  }
285
286  /**
287   * Specifies that each value (not key) stored in the map should be wrapped in a
288   * {@link WeakReference} (by default, strong references are used).
289   *
290   * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
291   * candidate for caching; consider {@link #softValues} instead.
292   *
293   * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
294   * comparison to determine equality of values. This technically violates the specifications of
295   * the methods {@link Map#containsValue containsValue},
296   * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
297   * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
298   * expect.
299   *
300   * @throws IllegalStateException if the value strength was already set
301   * @see WeakReference
302   */
303  @GwtIncompatible("java.lang.ref.WeakReference")
304  @Override
305  public MapMaker weakValues() {
306    return setValueStrength(Strength.WEAK);
307  }
308
309  /**
310   * Specifies that each value (not key) stored in the map should be wrapped in a
311   * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
312   * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
313   * demand.
314   *
315   * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
316   * #maximumSize maximum size} instead of using soft references. You should only use this method if
317   * you are well familiar with the practical consequences of soft references.
318   *
319   * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
320   * comparison to determine equality of values. This technically violates the specifications of
321   * the methods {@link Map#containsValue containsValue},
322   * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
323   * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
324   * expect.
325   *
326   * @throws IllegalStateException if the value strength was already set
327   * @see SoftReference
328   */
329  @GwtIncompatible("java.lang.ref.SoftReference")
330  @Override
331  public MapMaker softValues() {
332    return setValueStrength(Strength.SOFT);
333  }
334
335  MapMaker setValueStrength(Strength strength) {
336    checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
337    valueStrength = checkNotNull(strength);
338    if (strength != Strength.STRONG) {
339      // STRONG could be used during deserialization.
340      useCustomMap = true;
341    }
342    return this;
343  }
344
345  Strength getValueStrength() {
346    return firstNonNull(valueStrength, Strength.STRONG);
347  }
348
349  /**
350   * Specifies that each entry should be automatically removed from the map once a fixed duration
351   * has elapsed after the entry's creation, or the most recent replacement of its value.
352   *
353   * <p>When {@code duration} is zero, elements can be successfully added to the map, but are
354   * evicted immediately. This has a very similar effect to invoking {@link #maximumSize
355   * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
356   * a code change.
357   *
358   * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
359   * write operations. Expired entries are currently cleaned up during write operations, or during
360   * occasional read operations in the absense of writes; though this behavior may change in the
361   * future.
362   *
363   * @param duration the length of time after an entry is created that it should be automatically
364   *     removed
365   * @param unit the unit that {@code duration} is expressed in
366   * @throws IllegalArgumentException if {@code duration} is negative
367   * @throws IllegalStateException if the time to live or time to idle was already set
368   * @deprecated Caching functionality in {@code MapMaker} is being moved to
369   *     {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being
370   *     replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. Note that {@code
371   *     CacheBuilder} is simply an enhanced API for an implementation which was branched from
372   *     {@code MapMaker}.
373   */
374  @Deprecated
375  @Override
376  MapMaker expireAfterWrite(long duration, TimeUnit unit) {
377    checkExpiration(duration, unit);
378    this.expireAfterWriteNanos = unit.toNanos(duration);
379    if (duration == 0 && this.nullRemovalCause == null) {
380      // SIZE trumps EXPIRED
381      this.nullRemovalCause = RemovalCause.EXPIRED;
382    }
383    useCustomMap = true;
384    return this;
385  }
386
387  private void checkExpiration(long duration, TimeUnit unit) {
388    checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns",
389        expireAfterWriteNanos);
390    checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns",
391        expireAfterAccessNanos);
392    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
393  }
394
395  long getExpireAfterWriteNanos() {
396    return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
397  }
398
399  /**
400   * Specifies that each entry should be automatically removed from the map once a fixed duration
401   * has elapsed after the entry's last read or write access.
402   *
403   * <p>When {@code duration} is zero, elements can be successfully added to the map, but are
404   * evicted immediately. This has a very similar effect to invoking {@link #maximumSize
405   * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
406   * a code change.
407   *
408   * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
409   * write operations. Expired entries are currently cleaned up during write operations, or during
410   * occasional read operations in the absense of writes; though this behavior may change in the
411   * future.
412   *
413   * @param duration the length of time after an entry is last accessed that it should be
414   *     automatically removed
415   * @param unit the unit that {@code duration} is expressed in
416   * @throws IllegalArgumentException if {@code duration} is negative
417   * @throws IllegalStateException if the time to idle or time to live was already set
418   * @deprecated Caching functionality in {@code MapMaker} is being moved to
419   *     {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being
420   *     replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. Note that
421   *     {@code CacheBuilder} is simply an enhanced API for an implementation which was branched
422   *     from {@code MapMaker}.
423   */
424  @Deprecated
425  @GwtIncompatible("To be supported")
426  @Override
427  MapMaker expireAfterAccess(long duration, TimeUnit unit) {
428    checkExpiration(duration, unit);
429    this.expireAfterAccessNanos = unit.toNanos(duration);
430    if (duration == 0 && this.nullRemovalCause == null) {
431      // SIZE trumps EXPIRED
432      this.nullRemovalCause = RemovalCause.EXPIRED;
433    }
434    useCustomMap = true;
435    return this;
436  }
437
438  long getExpireAfterAccessNanos() {
439    return (expireAfterAccessNanos == UNSET_INT)
440        ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos;
441  }
442
443  Ticker getTicker() {
444    return firstNonNull(ticker, Ticker.systemTicker());
445  }
446
447  /**
448   * Specifies a listener instance, which all maps built using this {@code MapMaker} will notify
449   * each time an entry is removed from the map by any means.
450   *
451   * <p>Each map built by this map maker after this method is called invokes the supplied listener
452   * after removing an element for any reason (see removal causes in {@link RemovalCause}). It will
453   * invoke the listener during invocations of any of that map's public methods (even read-only
454   * methods).
455   *
456   * <p><b>Important note:</b> Instead of returning <i>this</i> as a {@code MapMaker} instance,
457   * this method returns {@code GenericMapMaker<K, V>}. From this point on, either the original
458   * reference or the returned reference may be used to complete configuration and build the map,
459   * but only the "generic" one is type-safe. That is, it will properly prevent you from building
460   * maps whose key or value types are incompatible with the types accepted by the listener already
461   * provided; the {@code MapMaker} type cannot do this. For best results, simply use the standard
462   * method-chaining idiom, as illustrated in the documentation at top, configuring a {@code
463   * MapMaker} and building your {@link Map} all in a single statement.
464   *
465   * <p><b>Warning:</b> if you ignore the above advice, and use this {@code MapMaker} to build a map
466   * or cache whose key or value type is incompatible with the listener, you will likely experience
467   * a {@link ClassCastException} at some <i>undefined</i> point in the future.
468   *
469   * @throws IllegalStateException if a removal listener was already set
470   * @deprecated Caching functionality in {@code MapMaker} is being moved to
471   *     {@link com.google.common.cache.CacheBuilder}, with {@link #removalListener} being
472   *     replaced by {@link com.google.common.cache.CacheBuilder#removalListener}. Note that {@code
473   *     CacheBuilder} is simply an enhanced API for an implementation which was branched from
474   *     {@code MapMaker}.
475   */
476  @Deprecated
477  @GwtIncompatible("To be supported")
478  <K, V> GenericMapMaker<K, V> removalListener(RemovalListener<K, V> listener) {
479    checkState(this.removalListener == null);
480
481    // safely limiting the kinds of maps this can produce
482    @SuppressWarnings("unchecked")
483    GenericMapMaker<K, V> me = (GenericMapMaker<K, V>) this;
484    me.removalListener = checkNotNull(listener);
485    useCustomMap = true;
486    return me;
487  }
488
489  /**
490   * Builds a thread-safe map, without on-demand computation of values. This method does not alter
491   * the state of this {@code MapMaker} instance, so it can be invoked again to create multiple
492   * independent maps.
493   *
494   * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
495   * be performed atomically on the returned map. Additionally, {@code size} and {@code
496   * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
497   * writes.
498   *
499   * @return a serializable concurrent map having the requested features
500   */
501  @Override
502  public <K, V> ConcurrentMap<K, V> makeMap() {
503    if (!useCustomMap) {
504      return new ConcurrentHashMap<K, V>(getInitialCapacity(), 0.75f, getConcurrencyLevel());
505    }
506    return (nullRemovalCause == null)
507        ? new MapMakerInternalMap<K, V>(this)
508        : new NullConcurrentMap<K, V>(this);
509  }
510
511  /**
512   * Returns a MapMakerInternalMap for the benefit of internal callers that use features of
513   * that class not exposed through ConcurrentMap.
514   */
515  @Override
516  @GwtIncompatible("MapMakerInternalMap")
517  <K, V> MapMakerInternalMap<K, V> makeCustomMap() {
518    return new MapMakerInternalMap<K, V>(this);
519  }
520
521  /**
522   * Builds a map that supports atomic, on-demand computation of values. {@link Map#get} either
523   * returns an already-computed value for the given key, atomically computes it using the supplied
524   * function, or, if another thread is currently computing the value for this key, simply waits for
525   * that thread to finish and returns its computed value. Note that the function may be executed
526   * concurrently by multiple threads, but only for distinct keys.
527   *
528   * <p>New code should use {@link com.google.common.cache.CacheBuilder}, which supports
529   * {@linkplain com.google.common.cache.CacheStats statistics} collection, introduces the
530   * {@link com.google.common.cache.CacheLoader} interface for loading entries into the cache
531   * (allowing checked exceptions to be thrown in the process), and more cleanly separates
532   * computation from the cache's {@code Map} view.
533   *
534   * <p>If an entry's value has not finished computing yet, query methods besides {@code get} return
535   * immediately as if an entry doesn't exist. In other words, an entry isn't externally visible
536   * until the value's computation completes.
537   *
538   * <p>{@link Map#get} on the returned map will never return {@code null}. It may throw:
539   *
540   * <ul>
541   * <li>{@link NullPointerException} if the key is null or the computing function returns a null
542   *     result
543   * <li>{@link ComputationException} if an exception was thrown by the computing function. If that
544   * exception is already of type {@link ComputationException} it is propagated directly; otherwise
545   * it is wrapped.
546   * </ul>
547   *
548   * <p><b>Note:</b> Callers of {@code get} <i>must</i> ensure that the key argument is of type
549   * {@code K}. The {@code get} method accepts {@code Object}, so the key type is not checked at
550   * compile time. Passing an object of a type other than {@code K} can result in that object being
551   * unsafely passed to the computing function as type {@code K}, and unsafely stored in the map.
552   *
553   * <p>If {@link Map#put} is called before a computation completes, other threads waiting on the
554   * computation will wake up and return the stored value.
555   *
556   * <p>This method does not alter the state of this {@code MapMaker} instance, so it can be invoked
557   * again to create multiple independent maps.
558   *
559   * <p>Insertion, removal, update, and access operations on the returned map safely execute
560   * concurrently by multiple threads. Iterators on the returned map are weakly consistent,
561   * returning elements reflecting the state of the map at some point at or since the creation of
562   * the iterator. They do not throw {@link ConcurrentModificationException}, and may proceed
563   * concurrently with other operations.
564   *
565   * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
566   * be performed atomically on the returned map. Additionally, {@code size} and {@code
567   * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
568   * writes.
569   *
570   * @param computingFunction the function used to compute new values
571   * @return a serializable concurrent map having the requested features
572   * @deprecated Caching functionality in {@code MapMaker} is being moved to
573   *     {@link com.google.common.cache.CacheBuilder}, with {@link #makeComputingMap} being replaced
574   *     by {@link com.google.common.cache.CacheBuilder#build}. See the
575   *     <a href="http://code.google.com/p/guava-libraries/wiki/MapMakerMigration">MapMaker
576   *     Migration Guide</a> for more details.
577   *     <b>This method is scheduled for deletion in February 2013.</b>
578   */
579  @Deprecated
580  @Override
581  public <K, V> ConcurrentMap<K, V> makeComputingMap(
582      Function<? super K, ? extends V> computingFunction) {
583    return (nullRemovalCause == null)
584        ? new MapMaker.ComputingMapAdapter<K, V>(this, computingFunction)
585        : new NullComputingConcurrentMap<K, V>(this, computingFunction);
586  }
587
588  /**
589   * Returns a string representation for this MapMaker instance. The exact form of the returned
590   * string is not specificed.
591   */
592  @Override
593  public String toString() {
594    Objects.ToStringHelper s = Objects.toStringHelper(this);
595    if (initialCapacity != UNSET_INT) {
596      s.add("initialCapacity", initialCapacity);
597    }
598    if (concurrencyLevel != UNSET_INT) {
599      s.add("concurrencyLevel", concurrencyLevel);
600    }
601    if (maximumSize != UNSET_INT) {
602      s.add("maximumSize", maximumSize);
603    }
604    if (expireAfterWriteNanos != UNSET_INT) {
605      s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
606    }
607    if (expireAfterAccessNanos != UNSET_INT) {
608      s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
609    }
610    if (keyStrength != null) {
611      s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
612    }
613    if (valueStrength != null) {
614      s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
615    }
616    if (keyEquivalence != null) {
617      s.addValue("keyEquivalence");
618    }
619    if (removalListener != null) {
620      s.addValue("removalListener");
621    }
622    return s.toString();
623  }
624
625  /**
626   * An object that can receive a notification when an entry is removed from a map. The removal
627   * resulting in notification could have occured to an entry being manually removed or replaced, or
628   * due to eviction resulting from timed expiration, exceeding a maximum size, or garbage
629   * collection.
630   *
631   * <p>An instance may be called concurrently by multiple threads to process different entries.
632   * Implementations of this interface should avoid performing blocking calls or synchronizing on
633   * shared resources.
634   *
635   * @param <K> the most general type of keys this listener can listen for; for
636   *     example {@code Object} if any key is acceptable
637   * @param <V> the most general type of values this listener can listen for; for
638   *     example {@code Object} if any key is acceptable
639   */
640  interface RemovalListener<K, V> {
641    /**
642     * Notifies the listener that a removal occurred at some point in the past.
643     */
644    void onRemoval(RemovalNotification<K, V> notification);
645  }
646
647  /**
648   * A notification of the removal of a single entry. The key or value may be null if it was already
649   * garbage collected.
650   *
651   * <p>Like other {@code Map.Entry} instances associated with MapMaker, this class holds strong
652   * references to the key and value, regardless of the type of references the map may be using.
653   */
654  static final class RemovalNotification<K, V> extends ImmutableEntry<K, V> {
655    private static final long serialVersionUID = 0;
656
657    private final RemovalCause cause;
658
659    RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) {
660      super(key, value);
661      this.cause = cause;
662    }
663
664    /**
665     * Returns the cause for which the entry was removed.
666     */
667    public RemovalCause getCause() {
668      return cause;
669    }
670
671    /**
672     * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
673     * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
674     */
675    public boolean wasEvicted() {
676      return cause.wasEvicted();
677    }
678  }
679
680  /**
681   * The reason why an entry was removed.
682   */
683  enum RemovalCause {
684    /**
685     * The entry was manually removed by the user. This can result from the user invoking
686     * {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link java.util.Iterator#remove}.
687     */
688    EXPLICIT {
689      @Override
690      boolean wasEvicted() {
691        return false;
692      }
693    },
694
695    /**
696     * The entry itself was not actually removed, but its value was replaced by the user. This can
697     * result from the user invoking {@link Map#put}, {@link Map#putAll},
698     * {@link ConcurrentMap#replace(Object, Object)}, or
699     * {@link ConcurrentMap#replace(Object, Object, Object)}.
700     */
701    REPLACED {
702      @Override
703      boolean wasEvicted() {
704        return false;
705      }
706    },
707
708    /**
709     * The entry was removed automatically because its key or value was garbage-collected. This can
710     * occur when using {@link #softValues}, {@link #weakKeys}, or {@link #weakValues}.
711     */
712    COLLECTED {
713      @Override
714      boolean wasEvicted() {
715        return true;
716      }
717    },
718
719    /**
720     * The entry's expiration timestamp has passed. This can occur when using {@link
721     * #expireAfterWrite} or {@link #expireAfterAccess}.
722     */
723    EXPIRED {
724      @Override
725      boolean wasEvicted() {
726        return true;
727      }
728    },
729
730    /**
731     * The entry was evicted due to size constraints. This can occur when using {@link
732     * #maximumSize}.
733     */
734    SIZE {
735      @Override
736      boolean wasEvicted() {
737        return true;
738      }
739    };
740
741    /**
742     * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
743     * {@link #EXPLICIT} nor {@link #REPLACED}).
744     */
745    abstract boolean wasEvicted();
746  }
747
748  /** A map that is always empty and evicts on insertion. */
749  static class NullConcurrentMap<K, V> extends AbstractMap<K, V>
750      implements ConcurrentMap<K, V>, Serializable {
751    private static final long serialVersionUID = 0;
752
753    private final RemovalListener<K, V> removalListener;
754    private final RemovalCause removalCause;
755
756    NullConcurrentMap(MapMaker mapMaker) {
757      removalListener = mapMaker.getRemovalListener();
758      removalCause = mapMaker.nullRemovalCause;
759    }
760
761    // implements ConcurrentMap
762
763    @Override
764    public boolean containsKey(@Nullable Object key) {
765      return false;
766    }
767
768    @Override
769    public boolean containsValue(@Nullable Object value) {
770      return false;
771    }
772
773    @Override
774    public V get(@Nullable Object key) {
775      return null;
776    }
777
778    void notifyRemoval(K key, V value) {
779      RemovalNotification<K, V> notification =
780          new RemovalNotification<K, V>(key, value, removalCause);
781      removalListener.onRemoval(notification);
782    }
783
784    @Override
785    public V put(K key, V value) {
786      checkNotNull(key);
787      checkNotNull(value);
788      notifyRemoval(key, value);
789      return null;
790    }
791
792    @Override
793    public V putIfAbsent(K key, V value) {
794      return put(key, value);
795    }
796
797    @Override
798    public V remove(@Nullable Object key) {
799      return null;
800    }
801
802    @Override
803    public boolean remove(@Nullable Object key, @Nullable Object value) {
804      return false;
805    }
806
807    @Override
808    public V replace(K key, V value) {
809      checkNotNull(key);
810      checkNotNull(value);
811      return null;
812    }
813
814    @Override
815    public boolean replace(K key, @Nullable V oldValue, V newValue) {
816      checkNotNull(key);
817      checkNotNull(newValue);
818      return false;
819    }
820
821    @Override
822    public Set<Entry<K, V>> entrySet() {
823      return Collections.emptySet();
824    }
825  }
826
827  /** Computes on retrieval and evicts the result. */
828  static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> {
829    private static final long serialVersionUID = 0;
830
831    final Function<? super K, ? extends V> computingFunction;
832
833    NullComputingConcurrentMap(
834        MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) {
835      super(mapMaker);
836      this.computingFunction = checkNotNull(computingFunction);
837    }
838
839    @SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred
840    @Override
841    public V get(Object k) {
842      K key = (K) k;
843      V value = compute(key);
844      checkNotNull(value, computingFunction + " returned null for key " + key + ".");
845      notifyRemoval(key, value);
846      return value;
847    }
848
849    private V compute(K key) {
850      checkNotNull(key);
851      try {
852        return computingFunction.apply(key);
853      } catch (ComputationException e) {
854        throw e;
855      } catch (Throwable t) {
856        throw new ComputationException(t);
857      }
858    }
859  }
860
861  /**
862   * Overrides get() to compute on demand. Also throws an exception when {@code null} is returned
863   * from a computation.
864   */
865  /*
866   * This might make more sense in ComputingConcurrentHashMap, but it causes a javac crash in some
867   * cases there: http://code.google.com/p/guava-libraries/issues/detail?id=950
868   */
869  static final class ComputingMapAdapter<K, V>
870      extends ComputingConcurrentHashMap<K, V> implements Serializable {
871    private static final long serialVersionUID = 0;
872
873    ComputingMapAdapter(MapMaker mapMaker,
874        Function<? super K, ? extends V> computingFunction) {
875      super(mapMaker, computingFunction);
876    }
877
878    @SuppressWarnings("unchecked") // unsafe, which is one advantage of Cache over Map
879    @Override
880    public V get(Object key) {
881      V value;
882      try {
883        value = getOrCompute((K) key);
884      } catch (ExecutionException e) {
885        Throwable cause = e.getCause();
886        Throwables.propagateIfInstanceOf(cause, ComputationException.class);
887        throw new ComputationException(cause);
888      }
889
890      if (value == null) {
891        throw new NullPointerException(computingFunction + " returned null for key " + key + ".");
892      }
893      return value;
894    }
895  }
896}