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