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