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