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(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s",
170        this.initialCapacity);
171    checkArgument(initialCapacity >= 0);
172    this.initialCapacity = initialCapacity;
173    return this;
174  }
175
176  int getInitialCapacity() {
177    return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
178  }
179
180  /**
181   * Specifies the maximum number of entries the map may contain. Note that the map <b>may evict an
182   * entry before this limit is exceeded</b>. As the map size grows close to the maximum, the map
183   * evicts entries that are less likely to be used again. For example, the map may evict an entry
184   * because it hasn't been used recently or very often.
185   *
186   * <p>When {@code size} is zero, elements can be successfully added to the map, but are evicted
187   * immediately. This has the same effect as invoking {@link #expireAfterWrite
188   * expireAfterWrite}{@code (0, unit)} or {@link #expireAfterAccess expireAfterAccess}{@code (0,
189   * unit)}. It can be useful in testing, or to disable caching temporarily without a code change.
190   *
191   * <p>Caching functionality in {@code MapMaker} has been moved to
192   * {@link com.google.common.cache.CacheBuilder}.
193   *
194   * @param size the maximum size of the map
195   * @throws IllegalArgumentException if {@code size} is negative
196   * @throws IllegalStateException if a maximum size was already set
197   * @deprecated Caching functionality in {@code MapMaker} has been moved to
198   *     {@link com.google.common.cache.CacheBuilder}, with {@link #maximumSize} being
199   *     replaced by {@link com.google.common.cache.CacheBuilder#maximumSize}. Note that {@code
200   *     CacheBuilder} is simply an enhanced API for an implementation which was branched from
201   *     {@code MapMaker}.
202   */
203  @Deprecated
204  @Override
205  MapMaker maximumSize(int size) {
206    checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
207        this.maximumSize);
208    checkArgument(size >= 0, "maximum size must not be negative");
209    this.maximumSize = size;
210    this.useCustomMap = true;
211    if (maximumSize == 0) {
212      // SIZE trumps EXPIRED
213      this.nullRemovalCause = RemovalCause.SIZE;
214    }
215    return this;
216  }
217
218  /**
219   * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
220   * table is internally partitioned to try to permit the indicated number of concurrent updates
221   * without contention. Because assignment of entries to these partitions is not necessarily
222   * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
223   * accommodate as many threads as will ever concurrently modify the table. Using a significantly
224   * higher value than you need can waste space and time, and a significantly lower value can lead
225   * to thread contention. But overestimates and underestimates within an order of magnitude do not
226   * usually have much noticeable impact. A value of one permits only one thread to modify the map
227   * at a time, but since read operations can proceed concurrently, this still yields higher
228   * concurrency than full synchronization. Defaults to 4.
229   *
230   * <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will
231   * change again in the future. If you care about this value, you should always choose it
232   * explicitly.
233   *
234   * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
235   * @throws IllegalStateException if a concurrency level was already set
236   */
237  @Override
238  public MapMaker concurrencyLevel(int concurrencyLevel) {
239    checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s",
240        this.concurrencyLevel);
241    checkArgument(concurrencyLevel > 0);
242    this.concurrencyLevel = concurrencyLevel;
243    return this;
244  }
245
246  int getConcurrencyLevel() {
247    return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
248  }
249
250  /**
251   * Specifies that each key (not value) stored in the map should be wrapped in a {@link
252   * WeakReference} (by default, strong references are used).
253   *
254   * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
255   * comparison to determine equality of keys, which is a technical violation of the {@link Map}
256   * specification, and may not be what you expect.
257   *
258   * @throws IllegalStateException if the key strength was already set
259   * @see WeakReference
260   */
261  @GwtIncompatible("java.lang.ref.WeakReference")
262  @Override
263  public MapMaker weakKeys() {
264    return setKeyStrength(Strength.WEAK);
265  }
266
267  MapMaker setKeyStrength(Strength strength) {
268    checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
269    keyStrength = checkNotNull(strength);
270    checkArgument(keyStrength != SOFT, "Soft keys are not supported");
271    if (strength != Strength.STRONG) {
272      // STRONG could be used during deserialization.
273      useCustomMap = true;
274    }
275    return this;
276  }
277
278  Strength getKeyStrength() {
279    return MoreObjects.firstNonNull(keyStrength, Strength.STRONG);
280  }
281
282  /**
283   * Specifies that each value (not key) stored in the map should be wrapped in a
284   * {@link WeakReference} (by default, strong references are used).
285   *
286   * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
287   * candidate for caching; consider {@link #softValues} instead.
288   *
289   * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
290   * comparison to determine equality of values. This technically violates the specifications of
291   * the methods {@link Map#containsValue containsValue},
292   * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
293   * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
294   * expect.
295   *
296   * @throws IllegalStateException if the value strength was already set
297   * @see WeakReference
298   */
299  @GwtIncompatible("java.lang.ref.WeakReference")
300  @Override
301  public MapMaker weakValues() {
302    return setValueStrength(Strength.WEAK);
303  }
304
305  /**
306   * Specifies that each value (not key) stored in the map should be wrapped in a
307   * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
308   * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
309   * demand.
310   *
311   * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
312   * #maximumSize maximum size} instead of using soft references. You should only use this method if
313   * you are well familiar with the practical consequences of soft references.
314   *
315   * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
316   * comparison to determine equality of values. This technically violates the specifications of
317   * the methods {@link Map#containsValue containsValue},
318   * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
319   * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
320   * expect.
321   *
322   * @throws IllegalStateException if the value strength was already set
323   * @see SoftReference
324   * @deprecated Caching functionality in {@code MapMaker} has been moved to {@link
325   *     com.google.common.cache.CacheBuilder}, with {@link #softValues} being replaced by {@link
326   *     com.google.common.cache.CacheBuilder#softValues}. Note that {@code CacheBuilder} is simply
327   *     an enhanced API for an implementation which was branched from {@code MapMaker}.
328   */
329  @Deprecated
330  @GwtIncompatible("java.lang.ref.SoftReference")
331  @Override
332  MapMaker softValues() {
333    return setValueStrength(Strength.SOFT);
334  }
335
336  MapMaker setValueStrength(Strength strength) {
337    checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
338    valueStrength = checkNotNull(strength);
339    if (strength != Strength.STRONG) {
340      // STRONG could be used during deserialization.
341      useCustomMap = true;
342    }
343    return this;
344  }
345
346  Strength getValueStrength() {
347    return MoreObjects.firstNonNull(valueStrength, Strength.STRONG);
348  }
349
350  /**
351   * Specifies that each entry should be automatically removed from the map once a fixed duration
352   * has elapsed after the entry's creation, or the most recent replacement of its value.
353   *
354   * <p>When {@code duration} is zero, elements can be successfully added to the map, but are
355   * evicted immediately. This has a very similar effect to invoking {@link #maximumSize
356   * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
357   * a code change.
358   *
359   * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
360   * write operations. Expired entries are currently cleaned up during write operations, or during
361   * occasional read operations in the absense of writes; though this behavior may change in the
362   * future.
363   *
364   * @param duration the length of time after an entry is created that it should be automatically
365   *     removed
366   * @param unit the unit that {@code duration} is expressed in
367   * @throws IllegalArgumentException if {@code duration} is negative
368   * @throws IllegalStateException if the time to live or time to idle was already set
369   * @deprecated Caching functionality in {@code MapMaker} has been moved to
370   *     {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being
371   *     replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. Note that {@code
372   *     CacheBuilder} is simply an enhanced API for an implementation which was branched from
373   *     {@code MapMaker}.
374   */
375  @Deprecated
376  @Override
377  MapMaker expireAfterWrite(long duration, TimeUnit unit) {
378    checkExpiration(duration, unit);
379    this.expireAfterWriteNanos = unit.toNanos(duration);
380    if (duration == 0 && this.nullRemovalCause == null) {
381      // SIZE trumps EXPIRED
382      this.nullRemovalCause = RemovalCause.EXPIRED;
383    }
384    useCustomMap = true;
385    return this;
386  }
387
388  private void checkExpiration(long duration, TimeUnit unit) {
389    checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns",
390        expireAfterWriteNanos);
391    checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns",
392        expireAfterAccessNanos);
393    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
394  }
395
396  long getExpireAfterWriteNanos() {
397    return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
398  }
399
400  /**
401   * Specifies that each entry should be automatically removed from the map once a fixed duration
402   * has elapsed after the entry's last read or write access.
403   *
404   * <p>When {@code duration} is zero, elements can be successfully added to the map, but are
405   * evicted immediately. This has a very similar effect to invoking {@link #maximumSize
406   * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
407   * a code change.
408   *
409   * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
410   * write operations. Expired entries are currently cleaned up during write operations, or during
411   * occasional read operations in the absense of writes; though this behavior may change in the
412   * future.
413   *
414   * @param duration the length of time after an entry is last accessed that it should be
415   *     automatically removed
416   * @param unit the unit that {@code duration} is expressed in
417   * @throws IllegalArgumentException if {@code duration} is negative
418   * @throws IllegalStateException if the time to idle or time to live was already set
419   * @deprecated Caching functionality in {@code MapMaker} has been moved to
420   *     {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being
421   *     replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. Note that
422   *     {@code CacheBuilder} is simply an enhanced API for an implementation which was branched
423   *     from {@code MapMaker}.
424   */
425  @Deprecated
426  @GwtIncompatible("To be supported")
427  @Override
428  MapMaker expireAfterAccess(long duration, TimeUnit unit) {
429    checkExpiration(duration, unit);
430    this.expireAfterAccessNanos = unit.toNanos(duration);
431    if (duration == 0 && this.nullRemovalCause == null) {
432      // SIZE trumps EXPIRED
433      this.nullRemovalCause = RemovalCause.EXPIRED;
434    }
435    useCustomMap = true;
436    return this;
437  }
438
439  long getExpireAfterAccessNanos() {
440    return (expireAfterAccessNanos == UNSET_INT)
441        ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos;
442  }
443
444  Ticker getTicker() {
445    return MoreObjects.firstNonNull(ticker, Ticker.systemTicker());
446  }
447
448  /**
449   * Specifies a listener instance, which all maps built using this {@code MapMaker} will notify
450   * each time an entry is removed from the map by any means.
451   *
452   * <p>Each map built by this map maker after this method is called invokes the supplied listener
453   * after removing an element for any reason (see removal causes in {@link RemovalCause}). It will
454   * invoke the listener during invocations of any of that map's public methods (even read-only
455   * methods).
456   *
457   * <p><b>Important note:</b> Instead of returning <i>this</i> as a {@code MapMaker} instance,
458   * this method returns {@code GenericMapMaker<K, V>}. From this point on, either the original
459   * reference or the returned reference may be used to complete configuration and build the map,
460   * but only the "generic" one is type-safe. That is, it will properly prevent you from building
461   * maps whose key or value types are incompatible with the types accepted by the listener already
462   * provided; the {@code MapMaker} type cannot do this. For best results, simply use the standard
463   * method-chaining idiom, as illustrated in the documentation at top, configuring a {@code
464   * MapMaker} and building your {@link Map} all in a single statement.
465   *
466   * <p><b>Warning:</b> if you ignore the above advice, and use this {@code MapMaker} to build a map
467   * or cache whose key or value type is incompatible with the listener, you will likely experience
468   * a {@link ClassCastException} at some <i>undefined</i> point in the future.
469   *
470   * @throws IllegalStateException if a removal listener was already set
471   * @deprecated Caching functionality in {@code MapMaker} has been moved to
472   *     {@link com.google.common.cache.CacheBuilder}, with {@link #removalListener} being
473   *     replaced by {@link com.google.common.cache.CacheBuilder#removalListener}. Note that {@code
474   *     CacheBuilder} is simply an enhanced API for an implementation which was branched from
475   *     {@code MapMaker}.
476   */
477  @Deprecated
478  @GwtIncompatible("To be supported")
479  <K, V> GenericMapMaker<K, V> removalListener(RemovalListener<K, V> listener) {
480    checkState(this.removalListener == null);
481
482    // safely limiting the kinds of maps this can produce
483    @SuppressWarnings("unchecked")
484    GenericMapMaker<K, V> me = (GenericMapMaker<K, V>) this;
485    me.removalListener = checkNotNull(listener);
486    useCustomMap = true;
487    return me;
488  }
489
490  /**
491   * Builds a thread-safe map. This method does not alter the state of this {@code MapMaker}
492   * instance, so it can be invoked again to create multiple 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} has been 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="https://github.com/google/guava/wiki/MapMakerMigration">MapMaker
576   *     Migration Guide</a> for more details.
577   */
578  @Deprecated
579  @Override
580  <K, V> ConcurrentMap<K, V> makeComputingMap(
581      Function<? super K, ? extends V> computingFunction) {
582    return (nullRemovalCause == null)
583        ? new MapMaker.ComputingMapAdapter<K, V>(this, computingFunction)
584        : new NullComputingConcurrentMap<K, V>(this, computingFunction);
585  }
586
587  /**
588   * Returns a string representation for this MapMaker instance. The exact form of the returned
589   * string is not specificed.
590   */
591  @Override
592  public String toString() {
593    MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
594    if (initialCapacity != UNSET_INT) {
595      s.add("initialCapacity", initialCapacity);
596    }
597    if (concurrencyLevel != UNSET_INT) {
598      s.add("concurrencyLevel", concurrencyLevel);
599    }
600    if (maximumSize != UNSET_INT) {
601      s.add("maximumSize", maximumSize);
602    }
603    if (expireAfterWriteNanos != UNSET_INT) {
604      s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
605    }
606    if (expireAfterAccessNanos != UNSET_INT) {
607      s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
608    }
609    if (keyStrength != null) {
610      s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
611    }
612    if (valueStrength != null) {
613      s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
614    }
615    if (keyEquivalence != null) {
616      s.addValue("keyEquivalence");
617    }
618    if (removalListener != null) {
619      s.addValue("removalListener");
620    }
621    return s.toString();
622  }
623
624  /**
625   * An object that can receive a notification when an entry is removed from a map. The removal
626   * resulting in notification could have occured to an entry being manually removed or replaced, or
627   * due to eviction resulting from timed expiration, exceeding a maximum size, or garbage
628   * collection.
629   *
630   * <p>An instance may be called concurrently by multiple threads to process different entries.
631   * Implementations of this interface should avoid performing blocking calls or synchronizing on
632   * shared resources.
633   *
634   * @param <K> the most general type of keys this listener can listen for; for
635   *     example {@code Object} if any key is acceptable
636   * @param <V> the most general type of values this listener can listen for; for
637   *     example {@code Object} if any key is acceptable
638   */
639  interface RemovalListener<K, V> {
640    /**
641     * Notifies the listener that a removal occurred at some point in the past.
642     */
643    void onRemoval(RemovalNotification<K, V> notification);
644  }
645
646  /**
647   * A notification of the removal of a single entry. The key or value may be null if it was already
648   * garbage collected.
649   *
650   * <p>Like other {@code Map.Entry} instances associated with MapMaker, this class holds strong
651   * references to the key and value, regardless of the type of references the map may be using.
652   */
653  static final class RemovalNotification<K, V> extends ImmutableEntry<K, V> {
654    private static final long serialVersionUID = 0;
655
656    private final RemovalCause cause;
657
658    RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) {
659      super(key, value);
660      this.cause = cause;
661    }
662
663    /**
664     * Returns the cause for which the entry was removed.
665     */
666    public RemovalCause getCause() {
667      return cause;
668    }
669
670    /**
671     * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
672     * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
673     */
674    public boolean wasEvicted() {
675      return cause.wasEvicted();
676    }
677  }
678
679  /**
680   * The reason why an entry was removed.
681   */
682  enum RemovalCause {
683    /**
684     * The entry was manually removed by the user. This can result from the user invoking
685     * {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link java.util.Iterator#remove}.
686     */
687    EXPLICIT {
688      @Override
689      boolean wasEvicted() {
690        return false;
691      }
692    },
693
694    /**
695     * The entry itself was not actually removed, but its value was replaced by the user. This can
696     * result from the user invoking {@link Map#put}, {@link Map#putAll},
697     * {@link ConcurrentMap#replace(Object, Object)}, or
698     * {@link ConcurrentMap#replace(Object, Object, Object)}.
699     */
700    REPLACED {
701      @Override
702      boolean wasEvicted() {
703        return false;
704      }
705    },
706
707    /**
708     * The entry was removed automatically because its key or value was garbage-collected. This can
709     * occur when using {@link #softValues}, {@link #weakKeys}, or {@link #weakValues}.
710     */
711    COLLECTED {
712      @Override
713      boolean wasEvicted() {
714        return true;
715      }
716    },
717
718    /**
719     * The entry's expiration timestamp has passed. This can occur when using {@link
720     * #expireAfterWrite} or {@link #expireAfterAccess}.
721     */
722    EXPIRED {
723      @Override
724      boolean wasEvicted() {
725        return true;
726      }
727    },
728
729    /**
730     * The entry was evicted due to size constraints. This can occur when using {@link
731     * #maximumSize}.
732     */
733    SIZE {
734      @Override
735      boolean wasEvicted() {
736        return true;
737      }
738    };
739
740    /**
741     * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
742     * {@link #EXPLICIT} nor {@link #REPLACED}).
743     */
744    abstract boolean wasEvicted();
745  }
746
747  /** A map that is always empty and evicts on insertion. */
748  static class NullConcurrentMap<K, V> extends AbstractMap<K, V>
749      implements ConcurrentMap<K, V>, Serializable {
750    private static final long serialVersionUID = 0;
751
752    private final RemovalListener<K, V> removalListener;
753    private final RemovalCause removalCause;
754
755    NullConcurrentMap(MapMaker mapMaker) {
756      removalListener = mapMaker.getRemovalListener();
757      removalCause = mapMaker.nullRemovalCause;
758    }
759
760    // implements ConcurrentMap
761
762    @Override
763    public boolean containsKey(@Nullable Object key) {
764      return false;
765    }
766
767    @Override
768    public boolean containsValue(@Nullable Object value) {
769      return false;
770    }
771
772    @Override
773    public V get(@Nullable Object key) {
774      return null;
775    }
776
777    void notifyRemoval(K key, V value) {
778      RemovalNotification<K, V> notification =
779          new RemovalNotification<K, V>(key, value, removalCause);
780      removalListener.onRemoval(notification);
781    }
782
783    @Override
784    public V put(K key, V value) {
785      checkNotNull(key);
786      checkNotNull(value);
787      notifyRemoval(key, value);
788      return null;
789    }
790
791    @Override
792    public V putIfAbsent(K key, V value) {
793      return put(key, value);
794    }
795
796    @Override
797    public V remove(@Nullable Object key) {
798      return null;
799    }
800
801    @Override
802    public boolean remove(@Nullable Object key, @Nullable Object value) {
803      return false;
804    }
805
806    @Override
807    public V replace(K key, V value) {
808      checkNotNull(key);
809      checkNotNull(value);
810      return null;
811    }
812
813    @Override
814    public boolean replace(K key, @Nullable V oldValue, V newValue) {
815      checkNotNull(key);
816      checkNotNull(newValue);
817      return false;
818    }
819
820    @Override
821    public Set<Entry<K, V>> entrySet() {
822      return Collections.emptySet();
823    }
824  }
825
826  /** Computes on retrieval and evicts the result. */
827  static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> {
828    private static final long serialVersionUID = 0;
829
830    final Function<? super K, ? extends V> computingFunction;
831
832    NullComputingConcurrentMap(
833        MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) {
834      super(mapMaker);
835      this.computingFunction = checkNotNull(computingFunction);
836    }
837
838    @SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred
839    @Override
840    public V get(Object k) {
841      K key = (K) k;
842      V value = compute(key);
843      checkNotNull(value, "%s returned null for key %s.", computingFunction, key);
844      notifyRemoval(key, value);
845      return value;
846    }
847
848    private V compute(K key) {
849      checkNotNull(key);
850      try {
851        return computingFunction.apply(key);
852      } catch (ComputationException e) {
853        throw e;
854      } catch (Throwable t) {
855        throw new ComputationException(t);
856      }
857    }
858  }
859
860  /**
861   * Overrides get() to compute on demand. Also throws an exception when {@code null} is returned
862   * from a computation.
863   */
864  /*
865   * This might make more sense in ComputingConcurrentHashMap, but it causes a javac crash in some
866   * cases there: http://code.google.com/p/guava-libraries/issues/detail?id=950
867   */
868  static final class ComputingMapAdapter<K, V>
869      extends ComputingConcurrentHashMap<K, V> implements Serializable {
870    private static final long serialVersionUID = 0;
871
872    ComputingMapAdapter(MapMaker mapMaker,
873        Function<? super K, ? extends V> computingFunction) {
874      super(mapMaker, computingFunction);
875    }
876
877    @SuppressWarnings("unchecked") // unsafe, which is one advantage of Cache over Map
878    @Override
879    public V get(Object key) {
880      V value;
881      try {
882        value = getOrCompute((K) key);
883      } catch (ExecutionException e) {
884        Throwable cause = e.getCause();
885        Throwables.propagateIfInstanceOf(cause, ComputationException.class);
886        throw new ComputationException(cause);
887      }
888
889      if (value == null) {
890        throw new NullPointerException(computingFunction + " returned null for key " + key + ".");
891      }
892      return value;
893    }
894  }
895}